the .get()
method returns a promise, which is executed asynchronously once you call .then()
. Because of this, the next line that gets executed is
console.log("Service Data :: " + data);
. Javascript does not wait for the promise to be resolved and instead just carries on with the next synchronous line which is the second console.
The way I usually go about this is passing the whole promise to the other component or better yet, I use the .valueChanges()
of the .doc()
which returns an observable, and use the async pipe in the component I'm passing to:
// Get Observable on document. Returns Observable<any>
const group$ = this.firestore.doc('/groups' + tempId).valueChanges();
You then have two options:
- Use
group$.subscribe();
- Pass
group$
to the component you want and use the async pipe there
First option:
// In your component:
let data;
group$.subscribe(doc => {
if (doc.exists) {
data = doc
console.log("Document data:", doc); // No need to call data().
} else {
console.log("No such document!");
},
error => console.log("Error getting document:", error);
)
Second option, passing into the component where you would like the observable to be evaluated and the data displayed:
<div *ngIf="group$ | async as doc">
Your html here {{ doc.someProperty }} further html here...
</div>
Personally, I prefer the second choice because it goes along with the framework nicely and keeps me from making asynchronous errors.
Have a look at angularfire2's Github repo for docs here. If there is no need to evaluate the observable by hand in code, I would not do this and let the framework handle it.
One final thing: If you use the observable and want to do some error handling when using the async pipe, you probably want to do so when creating the observable:
// Get Observable on document. Returns Observable<any>
// In error case, returns Observable of the error string
const group$ = this.firestore.doc('/groups' + tempId).valueChanges()
.pipe(
catchError(error => of(`Error getting document: ${error}`))
);
valueChanges()
and observables rather than Promises, if that's ok. – thomi