Hello I have a method in a the class below:
export class SearchService {
userUID: string;
searchItems: any;
private searchesCollection: AngularFirestor
You are working with async programming you cannot pause the execution of the code and your subscription will be resolved in future but you cannot predict when. console.log()
outside the subscribe
is executed before your subscription is resolved that's why it's undefined
and console.log()
inside subscribe call back is invoked after the subscription is resolved.
Refer this for better understanding.
what you can do is You can store the value in a class property and access it in your template.
getSearches() {
this.afAuth.authState.subscribe(user => {
this.userUID = user['uid'];
this.searchesCollection = this.db.collection(`users/${this.userUID}/searches`);
this.searchesCollection.valueChanges().subscribe(data => {
console.log(data); // works
this.searchItems=data;
});
});
console.log(this.searchItems); // undefined
return this.searchItems; //undefined
}
HTML
{{searchItems?.//property}}
or you can use async pipe
AsyncPipe accepts as an argument an observable
or a promise, calls subscribe
or attaches a then handler, then waits for the asynchronous result before passing it through to the caller.
getSearches() {
this.afAuth.authState.subscribe(user => {
this.userUID = user['uid'];
this.searchesCollection = this.db.collection(`users/${this.userUID}/searches`);
this.searchItems=this.searchesCollection.valueChanges();
}
HTML
{{item?.//property}}
LIVE DEMO