[英]Best method to “fork” observable
每當http auth API返回授權用戶時,我都需要設置currentUser: BehaviorSubject<>()
。 現在,我正在使用do
將新用戶發送到BehaviorSubject
但這似乎是完成此任務的一種骯臟方式。
是否有fork方法或類似方法會更新觀察者並返回原始的可觀察者?
我有的
public currentUser: BehaviorSubject<any> = new BehaviorSubject<any>(null);
authUser(email: String, password: String) {
return this.http.post('api.com/auth', {
email: email,
password: password
})
.do(user => this.currentUser.next(user))
}
我想要的是
return this.http.post('api.com/auth', {
email: email,
password: password
})
.fork(this.currentUser)
有不同的方法來解決這個問題,但在我看來,你應該使用subscribe
,而不是do
和authUser
不應返回任何東西。 為什么有兩種方式訪問同一事物(當前用戶)?
//private field and getter are optional but allows you to expose the
//field as an observable and not a subject
private _currentUser: BehaviorSubject<any> = new BehaviorSubject<any>(null);
get currentUser(): Observable<any> {
return this._currentUser;
}
authUser(email: String, password: String): void {
this.http.post('api.com/auth', {
email: email,
password: password
})
.subscribe(user => this._currentUser.next(user))
}
如果要進行清理(這是異步操作,因此您可能想知道何時完成),可以執行以下操作:
authUser(email: String, password: String): Observable<void> {
let requestObs = this.http.post('api.com/auth', {
email: email,
password: password
}).shareReplay();
requestObs.subscribe(user => this._currentUser.next(user));
return requestObs.map(user => null);
}
當然,如果您確實想要返回值,則可以刪除最后一個map語句。 最后,它與您的do
沒有太大的不同。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.