Angular/Ionic RXJS pipe/map 重新加载时未定义元素

Angular/Ionic RXJS pipe/map undefined element on reload

简单的管理员角色检查方法:

 isAdmin() {
    return this.userProfileObservable.pipe(map((profile: UserObject) => {
//Here I can place some delaying code and it works!!!
        return profile != null ? profile.role === 'admin' : false;
    }));
}

如果我从上一页导航到该页面并且路由器调用 AdminGuard,则工作正常:

 canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> {
    return this.auth.isAdmin();
}

Observables 在服务构造函数中初始化:

private _userProfileSubject: BehaviorSubject<UserObject>;
private _firebaseUserSubject: BehaviorSubject<firebase.User>;
private userProfileCollection: AngularFirestoreDocument<UserObject>;
public userProfileObservable: Observable<UserObject>;
private authObserver: firebase.Unsubscribe;

constructor(
    private afAuth: AngularFireAuth,
    private afs: AngularFirestore, ) {
    // Init observers with null initial value
    this._userProfileSubject = new BehaviorSubject(new UserObject()) as BehaviorSubject<UserObject>;
    this._firebaseUserSubject = new BehaviorSubject(null) as BehaviorSubject<firebase.User>;
    this.userProfileObservable = this._userProfileSubject.asObservable();

    this.authObserver = afAuth.auth.onAuthStateChanged((user) => {
        this._firebaseUserSubject.next(user);

        if (user == null) {
            this._userProfileSubject.next(null);
            return;
        }
        this.userProfileCollection = afs.collection<UserObject>('Users').doc(user.uid);
        // Monitor auth changes and update behaviorSubject -> observable <UserObject>
        this.userProfileCollection.snapshotChanges().subscribe((action => {
            const data = action.payload.data() as UserObject;
            data.uid = action.payload.id;
            this._userProfileSubject.next(data);
            return data;
        }));
    });
}

但是如果我重新加载页面/直接导航到受 AdminGuard 保护的路由,property/element in pipe -> map -> "profile" 由于某种原因变得未定义。

它好像还没有加载所有东西,好像我之前在 isAdmin 方法中执行了 "BIG HACK" 和 await/delay,然后它再次工作...

能否请您进行以下更改并尝试:

在您的服务中,让我们用 null 初始化 BehavorSubject;

this._userProfileSubject: BehaviorSubject<UserObject> = new BehaviorSubject(null);

然后更新您的 isAdmin() 方法,使其忽略 userProfileObservable 的第一个 'null' 值并等待直到它发出 NOT NULL 值 [为此使用 skipWhile() 运算符] 像这样:

isAdmin() {
            return this.userProfileObservable
                       .pipe(
                        //it will skip all null value until source sobservable emits a NOT NULL value; i.e. it will wait until your service's subscribe get the response and emits a NOT NULL value of UserObject
                        skipWhile(u => !u),
                        map((profile: UserObject) => {
                          //Here I can place some delaying code and it works!!!
                          return profile != null ? profile.role === 'admin' : false;
                        })
                      );
        }