我在项目中面临一个非常奇怪的行为,我有一个简单的Angular服务,其代码如下:
seatClick$ = new Subject<Seat>();
以及触发可观察对象的服务上的方法:
handleSeatClick(seat: Seat) {
this.seatClick$.next(seat);
}
可观察的逻辑很简单:
this.seatClick$.pipe(
exhaustMap((seat: Seat) => {
this.someFunctionThatThrowsException(); // this function throws ref exception
return of(null);
})
, catchError(err => {
console.log('error handled');
return of(null);
})
)
.subscribe(() => {
console.log('ok');
},
(error1 => {
console.log('oops');
})
);
这真的很奇怪,当调用“ someFunctionThatThrowsException”时,它引发一些ReferenceError异常,然后使用catchError捕获此异常,并触发next()事件。
但是,从这一刻开始,在可观察到的seatClick上停止响应,就好像它已完成一样,在该服务上调用handleSeatClick将不再响应。
我在这里想念什么?
答案 0 :(得分:1)
这是正确的行为,您需要repeat
运算符才能重新订阅。
this.seatClick$.pipe(
exhaustMap((seat: Seat) => {
this.someFunctionThatThrowsException();
return of(null);
})
// in case of an error the stream has been completed.
, catchError(err => {
console.log('error handled');
return of(null);
})
// now we need to resubscribe again
, repeat() // <- here
)
.subscribe(() => {
console.log('ok');
},
(error1 => {
console.log('oops');
})
);
如果您知道某件事可能会失败,则可以将其专用于内部流并在其中使用catchError
,那么您就不需要repeat
。
this.seatClick$.pipe(
// or exhaustMap, or mergeMap or any other stream changer.
switchMap(seal => of(seal).pipe(
exhaustMap((seat: Seat) => {
this.someFunctionThatThrowsException();
return of(null);
})
, catchError(err => {
console.log('error handled');
return of(null);
})
)),
// now switchMap always succeeds with null despite an error happened inside
// therefore we don't need `repeat` outside and our main stream
// will be completed only when this.seatClick$ completes
// or throws an error.
)
.subscribe(() => {
console.log('ok');
},
(error1 => {
console.log('oops');
})
);