如预期的那样,以下代码在5秒钟后发出42:
const valueObservable = of(42).pipe(delay(5000));
valueObservable.subscribe((value) => console.log(value));
但是,这会在订阅后立即引发版本错误:
const throwingObservable = throwError(new Error('My Error')).pipe(delay(5000));
throwingObservable.subscribe((value) => console.log(value), (error) => console.error(error));
为什么会这样?如何延迟抛出错误?
答案 0 :(得分:2)
Rxjs错误是异常,它会立即停止流并让您捕获它以对意外的事件做出反应。我想除了catchError
解决方案1:在抛出错误之前操纵流。
const throwingObservable = throwError(new Error('My Error'));
timer(5000).pipe(mergeMap(e => throwingObservable))
.subscribe((value) => console.log(value), (error) => console.error(error));
解决方案2:捕获错误,延迟流,然后再次分派
throwingObservable.pipe(
// We catch the error, we delay by adding timer stream, then we mergeMap to the error.
catchError(e => timer(1000).pipe(mergeMap(t => throwError(e)))
)).subscribe(console.log, console.error);
答案 1 :(得分:1)
我发现了(IMO)可以更轻松地延迟引发错误的方法:
const throwingObservable = of(42).pipe(
delay(5000),
switchMap(() => throwError(new Error('My Error')))
);
throwingObservable.subscribe(
value => console.log(value),
error => console.error(error)
);
答案 2 :(得分:0)
我遇到了类似的问题,发现了这个 github 问题:https://github.com/Reactive-Extensions/RxJS/issues/648
更新到我的用例,它会是这样的:
const throwingObservable = throwError(new Error('My Error'))
.pipe(
materialize(),
delay(4000),
dematerialize()
);
throwingObservable.subscribe(console.log, console.error);
延迟 4 秒后抛出