0
votes

Hi I am trying to get a single document in firebase however it is giving me an error

Property 'then' does not exist on type 'Observable<DocumentSnapshot>'.

I have followed the documentation on firebase https://firebase.google.com/docs/firestore/query-data/get-data

My service.ts code is

import { Injectable } from '@angular/core';
import { AngularFirestore } from '@angular/fire/firestore';

@Injectable({
  providedIn: 'root'
})
export class ViewReportService {

 

     constructor(private firestore: AngularFirestore) { }
    
      getPassengerReport(myDocument) {
        const passengerRef = this.firestore.collection("newPassenger").doc(myDocument);
        const data = passengerRef.get().then(function (doc) {
          console.log("Cached document data:", doc.data());
        }).catch(function (error) {
          console.log("Error getting cached document:", error);
        });
        return data
      }

}

Angular Component Code

    passengerData = this.service.getPassengerReport(passengerDocumentID);
    console.log(passengerData)
    }
2

2 Answers

2
votes

.then is for the promise. Observable is a different thing than the promise, and you need to convert observable into promise like something.toPromise().then().

But important thing you need to consider the subscribe, so you may need to add an operator first() for it.

So code should be something.pipe(first()).toPromise().then()

Please try the above thing.

2
votes

You need to consider that you are using Angular. One of the best practices in Angular is to use Observable rather than promises

Lets convert your function to return an Obervable

import { Injectable } from '@angular/core';
import { AngularFirestore } from '@angular/fire/firestore';

@Injectable({
  providedIn: 'root'
})
export class ViewReportService {
  constructor(private firestore: AngularFirestore) { }
  getPassengerReport = (myDocument) => 
    this.firestore.collection("newPassenger").doc(myDocument).get()
}

In the above we have defined getPassengerReport as a function that returns the line this.firestore.collection("newPassenger").doc(myDocument).get() using ES6 syntax

In your component file you can have

 passengerData$ = this.service.getPassengerReport(passengerDocumentID);
    

And in you can wrap your html with

<ng-container *ngIf='passengerData$ | async as passengerData'>

  <!-- HTML CODE HERE -->

</ng-container>

We use async pipe to subscribe to the Observable