我有:
getSth(): void {
this.service.functionName.pipe(
takeUntil(this.destroy$),
distinctUntilChanged(),
map(res => res.event)
).subscribe(((response) => {
this.getAnother(response);
})); }
getAnother(response): void {
this.anotherService.anotherFunctionName(response).subscribe((res) => {
this.result = res;
}); }
我知道在訂閱中撰寫訂閱不是一個好的解決方案。如何解決?
uj5u.com熱心網友回復:
讓我們使用switchMap:
getSth(): void {
this.service.functionName.pipe(
takeUntil(this.destroy$),
distinctUntilChanged(),
map(res => res.event),
switchMap(response =>
this.anotherService.anotherFunctionName(response)
)
).subscribe(response => this.result = response);
}
uj5u.com熱心網友回復:
您應該盡可能地將 observable 鏈接在一起,在頂層只有一個訂閱者。對此有很多很好的理由,超出了本答案的范圍。
您可以重構您的代碼以從您的函式回傳一個 observable(tap用于執行任何副作用,例如更新狀態),并將switchMap其鏈接到現有的 observable 上。
getSth(): void {
this.service.functionName.pipe(
takeUntil(this.destroy$),
distinctUntilChanged(),
map(res => res.event),
switchMap(response => this.getAnother(response))
).subscribe();
}
// TODO: return correct type in Observable<T>
getAnother(response): Observable<any> {
return this.anotherService.anotherFunctionName(response).pipe(
tap(res => this.result = res)
);
}
uj5u.com熱心網友回復:
你有更多的選擇,有一些*map運算子,以不同的方式處理流程。通過您的示例,您可以使用switchMap,它取消您正在運行的可觀察物件(在您的示例中getAnother)。檔案中有一個Operator Decision Tree,試試看,它很有幫助。
你得到switchMap這個邏輯:
- 我有一個現有的 Observable,并且
- 我想為每個值啟動一個新的 Observable
- 并在新值到達時取消之前嵌套的 Observable
- 其中為每個值計算嵌套的 Observable
另一個注意事項,你應該把你的takeUntil放在最后。
你可以這樣寫:
getSth(): void {
this.service.functionName.pipe(
// If service.functionName returns a new object every time distinctUntilChanged will do nothing as references won't be the same.
// distinctUntilChanged(),
switchMap(resp => this.anotherService.anotherFunctionName(resp.event))
takeUntil(this.destroy$),
).subscribe((result) => {
this.result = result;
}));
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/349599.html
標籤:有角的 rxjs 订阅 rxjs-observables rxjs-订阅
