我试图获取BehaviorSubject的值。返回值,但如何使用它们在返回true / false语句中使用它们。
BehaviorSubject {_isScalar: false, observers: Array(0), closed: false, isStopped: false, hasError: false, …}
closed:false
hasError:false
isStopped:false
observers:[Subscriber]
thrownError:null
value:(...)
_isScalar:false
_value:Array(3)
0:"name@gmail.com"
1:"Bob Smith"
2:{adminUser: false, basicUser: true} length:3
__proto__:Array(0)
__proto__:Subject
我的行为主题有以下内容发送给它。我为什么一开始就变空了。
user: BehaviorSubject<User> = new BehaviorSubject<User>(null);
//用户的行为角色。
this.afAuth.authState
.switchMap(auth => {
if (auth) {
/// signed in
const authData = this.db.list<User>('users/' + auth.uid).valueChanges();
console.log(authData);
return this.db.list<User>('users/' + auth.uid).valueChanges();
} else {
/// not signed in
return Observable.of(null);
}
})
// .subscribe(console.log); // check the subscription
.subscribe((userData) => {
console.log(userData);
this.user.next(userData);
// this.user.next(user);
// console.log(this.user.next(userData));
});
}
我遇到问题的结果:
Check Value false authguard.service.ts:39
Route was False authguard.service.ts:26
Check Value true
我运行console.log并且值首先显示为null因此具有错误响应。然后它再次运行并变为真。这一切都发生在最初运行页面后。我需要在加载时检查值为true。
答案 0 :(得分:0)
您应该能够使用.getValue()调用BehaviorSubject的名称 所以像:
let x = new BehaviorSubject<any>;
...
x.getValue()
答案 1 :(得分:0)
我遇到了同样的问题。我总是得到我的初始值(为空),而永远不会得到发射的值。 skip()
方法无济于事,但skipWhile()
方法才是诀窍。
behaviorSubject.pipe(
skipWhile(value => !value), // skip null values
take(1)) // in my case, I need the value only once
.subscribe(value => doYourWork());