rxjs error handling > on catchError source stops emitting
rxjs
(此处为现场演示)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | 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$ } |
1 | {{ value$ | async }} |
异步管道订阅的
在以下情况下,这在实践中对我很重要,在这种情况下,每次发出路线参数时我们都会加载新数据。假设我们导航到引发错误的路线(例如404、500等),我不希望事件流停止发出,因为那样我就无法导航回任何其他页面。我只想优雅地处理错误并继续侦听路由更改。
1 2 3 4 5 6 7 | this.foo$ = this._route.params.pipe( map(params => params.id), switchMap(id => this._fooServerClient.getOneById(id)), catchError(err => { return of(undefined) }) ) |
如果在Observable管道中发生异常,则是根据Observable的设计,相应的Observable [引发错误]将处于错误状态,并且无法发出新的/进一步的值[即就像是退订]。
现在,为了保持您的外部可观察的生命[继续发出新值],然后以内部可观察的方式处理错误[即在内部可观察管道中使用
1 2 3 4 5 6 7 8 9 10 11 12 13 | this.foo$ = this._route.params .pipe( map(params => params.id), switchMap(id => { return this._fooServerClient.getOneById(id) .pipe( catchError(err => { return of(undefined); }) ) }), ); |
内部可观察管道中的