我知道有很多關于標題主題的問題,但我無法找到有助于我跟進的清晰簡潔的問題/回復。
假設我們有 x 數量的 web api 呼叫回傳 observables Observable<cs[]>... 見
init() {
this.service.serviceA().subscribe({
next: (as) => {
this.as = as;
this.service.serviceB().subscribe({
next: (bs) => {
this.bs = bs;
this.service.serviceC().subscribe({
next: (cs) => {
this.cs = cs;
this.restructureABCs();
},
error: (e) => this.notification.showError('Failed to load cs! Error: ' e.messageerror)
});
},
error: (e) => this.notification.showError('Failed to load bs! Error: ' e.messageerror)
});
},
error: (e) => this.notification.showError('Failed to load as! Error: ' e.messageerror)
})
}
函式restructureABCs()依賴于 as/bs & cs。因為,bs & cs 不相互依賴。當前的實作很丑陋,可以改進,但我不確定應該使用哪個運算子。使用 concatMap 對我來說沒有意義,因為(根據我可能有缺陷的理解)多個流將被合并為一個,這是我不想要的。我只需要確保在呼叫restructureABCs()函式之前加載 as/bs & cs 。
Angular13,rxjs7.4
uj5u.com熱心網友回復:
如果 BS、CS、AS 不相互依賴,它們可以并行運行,您只需要確保所有這些 Observable 都完成以運行 restructureABCs()。因此,您可以在這種情況下使用 combineLatest/forkJoin。
combineLatest([
this.service.serviceA().pipe(catchError(er => ...)),
this.service.serviceB().pipe(catchError(er => ...)),
this.service.serviceC().pipe(catchError(er => ...))
]).subscribe(response => {
this.as = response[0];
this.bs = response[1];
this.cs = response[2];
restructureABCs()
})
uj5u.com熱心網友回復:
這是我使用forkJoin提出的解決方案。
as : Array<as>;
bs : Array<bs>;
cs : Array<cs>;
as$: Observable<as[]> = this.service.serviceA();
bs$: Observable<bs[]> = this.service.serviceB();
cs$: Observable<cs[]> = this.service.serviceC();
init() {
forkJoin([
this.as$.pipe(catchError(er => of({errMsg: 'Failed to load as! Error: ', error: er}))),
this.bs$.pipe(catchError(er => of({errMsg: 'Failed to load bs! Error: ', error: er}))),
this.cs$.pipe(catchError(er => of({errMsg: 'Failed to load cs! Error: ', error: er})))
])
.subscribe({
next: ([a, b, c]) => {
this.as = a as Array<as>;
this.bs = b as Array<bs>;
this.cs = c as Array<cs>;
this.restructureABCs();
},
error: (e) => this.notification.showError(e.errMsg)
});
}
找到有關處理 forkjoin 錯誤的有用文章:
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/409354.html
標籤:
