[英]rxjs error handling > on catchError source stops emitting
我對rxjs catchError
運算符有點困惑。 這是一個使用Angular的簡單示例:
( 這里有現場演示)
import { Component } from '@angular/core';
import { of, timer } from 'rxjs'
import { tap, catchError } from 'rxjs/operators'
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
})
export class AppComponent {
constructor() {
const source$ = timer(1000, 1000).pipe(tap(n => {
if (n === 3) {
throw new Error('n === 3')
}
}))
this.value$ = source$.pipe(catchError(err => {
return of(42)
}))
}
value$
}
{{ value$ | async }}
異步管道訂閱到的source$
可觀察到的發出0,1,2,然后出現錯誤。 這個錯誤在catchError
運算符中捕獲,該catchError
符將錯誤地吞下並發出42。我想我明白。 但是,發射隨后停止了(我原以為是4,5,6,...)。 有人可以解釋為什么這種情況不會發生,以及是否有任何方法可以實現這種行為嗎?
在以下情況下,這在實踐中對我很重要,在這種情況下,每次發出路線參數時我們都會加載新數據。 假設我們導航到引發錯誤的路線(例如404、500等),我不希望事件流停止發出,因為那樣我就無法導航回任何其他頁面。 我只想優雅地處理錯誤並繼續偵聽路由更改。
this.foo$ = this._route.params.pipe(
map(params => params.id),
switchMap(id => this._fooServerClient.getOneById(id)),
catchError(err => {
return of(undefined)
})
)
如果Observable管道中發生異常,則是根據Observable的設計,相應的Observable [引發錯誤]將處於錯誤狀態,並且無法發出新的/進一步的值[即,就像取消訂閱一樣]。
現在,要保持外部可觀察的活動(即繼續發出新值),然后處理內部可觀察的錯誤[即在內部可觀察的管道中使用catchError
運算符,如下所示:
this.foo$ = this._route.params
.pipe(
map(params => params.id),
switchMap(id => {
return this._fooServerClient.getOneById(id)
.pipe(
catchError(err => {
return of(undefined);
})
)
}),
);
內部可觀察管道中具有catchError
將保持外部可觀察活動(即即使內部可觀察拋出異常,也繼續發出新值)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.