我有一个事件发射器testEvent。testEvent有一个管道链,并在该链中引发错误。但我也在链中的两个地方发现了错误。尽管如此,我testEvent的自动取消订阅。
有人可以解释为什么吗?
import { Component, EventEmitter } from '@angular/core';
import {map} from 'rxjs/operators';
import {catchError, switchMap} from 'rxjs/internal/operators';
import {forkJoin, of} from 'rxjs';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = 'Angular';
testEvent$ = new EventEmitter();
ngOnInit(){
this.testEvent$
.pipe(
map((x) => {
alert();
throw "error";
},
catchError((e)=>{
console.log(e);
return of(1);
})
)
)
.subscribe(null, (e)=>{
console.log(e);
})
}
test(){
this.testEvent$.emit(''); //works only once
}
}
Run Code Online (Sandbox Code Playgroud)
问题是您of(1)在错误处理程序中返回。然后订阅重新订阅那个 Observable,它只发出一次。它不再订阅testEvent$. 因此它在一次发射后完成。
catchErrorcallback 实际上接收原始 Observable 作为第二个参数。如果您想继续收听原始 observable,请从错误处理程序返回。
catchError((e, originalObservable)=>{
console.log(e);
return originalObservable;
})
Run Code Online (Sandbox Code Playgroud)
关于回调的RxDocs:
一个将 err 作为参数的函数,它是错误,并被捕获,它是源 observable,以防您想通过再次返回它来“重试”该 observable。选择器返回的任何 observable 都将用于继续 observable 链。
| 归档时间: |
|
| 查看次数: |
319 次 |
| 最近记录: |