[英]How to wait for a subscription to complete angular
我有一個auth服務,我想在返回之前使用angularfire從firebase檢索用戶記錄,但數據返回得太晚。 我添加了“.filter(data => data!== undefined)”,但它沒有讓它等待。
this.authState = this.afAuth.authState;
this.authState.subscribe(user => {
if (user) {
this.currentUser = user;
this.userid = this.currentUser.uid;
this.displayname = this.currentUser.displayName;
this.path = '/AU/user/' + this.currentUser.uid + '/';
this.exists = this.af.object(this.path);
// this line of code returns data after the navbar
// and user components have started which is too late.
// The filter was added to try to get it wait for the data.
this.exists.filter(data => data !== undefined).subscribe(x => {
if (x && (x.$value !== null)) {
this.mobile = x.mobile;
this.userid = x.userid;
this.name = x.name;
this.email = x.email;
this.confirm = x.confirm;
// the fields below are undefined in the console log
console.log( 'email', this.email, 'name', this.name)
} else {
this.currentUser = null;
}
});
在谷歌搜索這個問題時,我發現也許我需要映射響應,但它沒有任何區別。 以下是我使用的代碼
this.exists.map(response => this.response$)
.filter(data => data !== undefined)
.subscribe(x => {
我嘗試比較“undefined”和“null”。 我已經用完了想法,請幫忙。
如何使用flatMap()
,像這樣?
import 'rxjs/add/operator/mergeMap`;
this.exists.flatMap(response => {
this.response$
.catch(error => {
console.error(error);
return Rx.Observable.empty();
});
});
我導入了mergeMap
運算符,盡管我們將使用flatMap
,因為在升級到RC 6和RxJS Beta 11以及缺少rxjs flatmap之后缺少flatMap 。
如果您願意,請閱讀map vs flatMap 。
this.exists.flatMap(response => this.response$)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.