你正在和
async programming
您不能暂停代码的执行,您的订阅将在将来得到解决,但您不能预测何时。
console.log()
在
subscribe
在解决订阅之前执行,因此未定义
和
控制台.log()
在解析订阅后调用内部订阅回调。
参考
this
为了更好的理解。
您可以将值存储在类属性中并在模板中访问它。
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}}
或者你可以用
async pipe
AsyncPipe接受
observable
或者一个承诺,一个电话
订阅
或者附加一个then处理程序,然后等待异步结果,然后再将其传递给调用方。
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
<ng-container *ngFor="let item of searchItems|async">
{{item?.//property}}
<ng-container>
LIVE DEMO