[英]Get the value of a BehaviorSubject
我正在嘗試獲取 BehaviorSubject 的值。 返回值,但我如何利用它們在 return 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 因此有一個錯誤的響應。 然后它再次運行並變為真。 這一切都發生在最初運行頁面之后。 我需要我的檢查值在加載時為真。
您應該能夠使用 .getValue() 調用 BehaviorSubject 的名稱,例如:
let x = new BehaviorSubject<any>;
...
x.getValue()
我遇到了同樣的問題。 我總是得到我的初始值(它是空的),而不是發出的值。 skip()
-method 對我沒有幫助,但skipWhile()
-method 是訣竅。
behaviorSubject.pipe(
skipWhile(value => !value), // skip null values
take(1)) // in my case, I need the value only once
.subscribe(value => doYourWork());
如果可能,那么最好的解決方案是切換到大小為 1 的ReplaySubject
。您不再需要.skip()
或.skipeWhile()
了。
這是一個例子。
// replaySubjects have no initial value
let subject = new ReplaySubject<YourType>(1);
subject.pipe(take(1)).
// no null-values anymore!
.subscribe(value => doYourStuff());
// subscribers dont get any value until a next()-call
subject.next(youValue);
// and you can hide some methods, when you declare it as observable or subject
// hide replaySubject specific informations
let publicSubject: Subject<YourType> = subject;
// hide subject informations (like .next())
let publicSubject2: Observable<YourType> = subject;
我已經正式回答了我的問題。 可能不是正確的方法,但它確實有效。
來自rxjs的BehaviorSubject在該特定時間流中生成初始值和當前值。 現在,如果您想繞過初始值(在我的情況下為null ),那么在訂閱它之前,請確保使用 跳過運算符。
在這種情況下,我使用它來跳過第一個值 skip(1)。
// RxJS v6+
import { interval } from 'rxjs';
import { skip } from 'rxjs/operators';
//emit every 1s
const source = interval(1000);
//skip the first 5 emitted values
const example = source.pipe(skip(5));
//output: 5...6...7...8........
const subscribe = example.subscribe(val => console.log(val));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.