当另一个发出值时可观察到 RxJS 错误
RxJS Error Observable when another emits value
我在这里尝试做的人为示例:
const source = interval(1000);
const errorWhenThisEmits = timer(2500);
source.pipe(/* someOperatorHere? */).subscribe({
next: () => console.log('next!'),
error: (err) => console.log(err)
});
// desired outcome:
// 1000ms: next!
// 2000ms: next!
// 2500ms: error message
当第二个 observable 发出值时,是否可能导致源 observable 出错?
takeUntil
接近,但完成而不是错误。
发现takeUntil
如果通知器可观察对象出错,父可观察对象也会出错。
const source = interval(1000);
// added switchMap to throwError
const notifier = timer(2500).pipe(switchMap(() => throwError('error!')));
source.pipe(takeUntil(notifier)).subscribe({
next: (data) => console.log(data),
error: (err) => console.log(err)
});
这输出:
0
1
error!
您可以合并可观察对象
const source = interval(1000);
const notifier = timer(2500).pipe(switchMap(() => throwError("error message")));
merge(source, notifier).subscribe({
next: () => console.log("next!"),
error: err => console.log(err)
});
查看 stackblitz:https://stackblitz.com/edit/rxjs-ony9vx?file=index.ts
我在这里尝试做的人为示例:
const source = interval(1000);
const errorWhenThisEmits = timer(2500);
source.pipe(/* someOperatorHere? */).subscribe({
next: () => console.log('next!'),
error: (err) => console.log(err)
});
// desired outcome:
// 1000ms: next!
// 2000ms: next!
// 2500ms: error message
当第二个 observable 发出值时,是否可能导致源 observable 出错?
takeUntil
接近,但完成而不是错误。
发现takeUntil
如果通知器可观察对象出错,父可观察对象也会出错。
const source = interval(1000);
// added switchMap to throwError
const notifier = timer(2500).pipe(switchMap(() => throwError('error!')));
source.pipe(takeUntil(notifier)).subscribe({
next: (data) => console.log(data),
error: (err) => console.log(err)
});
这输出:
0
1
error!
您可以合并可观察对象
const source = interval(1000);
const notifier = timer(2500).pipe(switchMap(() => throwError("error message")));
merge(source, notifier).subscribe({
next: () => console.log("next!"),
error: err => console.log(err)
});
查看 stackblitz:https://stackblitz.com/edit/rxjs-ony9vx?file=index.ts