Простой метод проверки роли администратора:
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();
}
Наблюдаемые инициализируются в конструкторе службы:
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, свойство/элемент в канале -> карта -> «профиль» по какой-то причине становится неопределенным.
Как будто еще не все загружено, как будто я выполняю "BIG HACK" и жду/откладываю перед этим в методе isAdmin, тогда он снова работает...





Не могли бы вы внести следующие изменения и попробовать:
В вашем сервисе давайте инициализируем BehavorSubject нулевым значением;
this._userProfileSubject: BehaviorSubject<UserObject> = new BehaviorSubject(null);
Затем обновите метод isAdmin() таким образом, чтобы он игнорировал самое первое «нулевое» значение userProfileObservable и ждал, пока он не выдаст значение 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;
})
);
}