我有一个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”。我已经用完了想法,请帮忙。
答案 0 :(得分:2)
如何使用flatMap()
呢?
import 'rxjs/add/operator/mergeMap`;
this.exists.flatMap(response => {
this.response$
.catch(error => {
console.error(error);
return Rx.Observable.empty();
});
});
我导入了mergeMap
运算符,尽管由于flatMap missing after upgrading to RC 6 and RxJS Beta 11和rxjs flatmap missing我们将使用flatMap
。
如果您愿意,请阅读map vs flatMap。
答案 1 :(得分:1)
this.exists.flatMap(response => this.response$)