您好,我在下面的课程中有一个方法:
export class SearchService { userUID: string; searchItems: any; private searchesCollection: AngularFirestoreCollection; constructor( private db: AngularFirestore,private afAuth: AngularFireAuth,) { } getSearches() { this.afAuth.authState.subscribe(user => { this.userUID = user['uid']; this.searchesCollection = this.db.collection(`users/${this.userUID}/searches`); this.searchItems = this.searchesCollection.valueChanges().subscribe(data => { console.log(data); // works return data; }); }); console.log(this.searchItems); // undefined return this.searchItems; //undefined } }
我的问题是return语句,它返回undefined.它上面几行的console.log(data)返回我想要的值.我想知道为什么我会变得不确定.这可能是一个范围问题,但我似乎无法弄明白.它可能是一个我忽略的简单错误.有什么建议么?
谢谢!
您正在使用
async programming ,您无法暂停代码的执行,您的订阅将在未来解决,但您无法预测何时.订阅之外的console.log()在您的订阅被解决之前执行,这就是为什么它是未定义的,并且在订阅被解析之后调用subscribe回调中的console.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}}
或者您可以使用异步管道
AsyncPipe接受一个observable或promise作为参数,调用subscribe或附加一个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>