我有一个事件发射器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
}
}
最佳答案
问题是您在错误处理程序中返回 of(1)
。然后订阅重新订阅该 Observable,该 Observable 只发出一次。它不再订阅 testEvent$
。因此它在一次发射后完成。
catchError
回调实际上接收原始 Observable 作为第二个参数。如果您想继续收听原始的 observable,请从错误处理程序中返回。
catchError((e, originalObservable)=>{
console.log(e);
return originalObservable;
})
RxDocs关于回调:
a function that takes as arguments err, which is the error, and caught, which is the source observable, in case you'd like to "retry" that observable by returning it again. Whatever observable is returned by the selector will be used to continue the observable chain.
关于angular - 尽管发现错误,rxjs 仍发生取消订阅,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57609812/