假设有如下代码模拟我目前的环境,
在线查看地址:https://stackblitz.com/edit/r...
import { of, BehaviorSubject } from 'rxjs';
import { switchMap, map, catchError, tap } from 'rxjs/operators';
/**
* 模拟通过http请求获取数据
*/
function getData(value) {
return of(value)
.pipe(map(value => {
// 模拟http请求报错
if(value % 2 === 0) {
throw new Error('不是奇数');
}
return value;
}));
}
const subject = new BehaviorSubject<number>(1);
subject
.pipe(switchMap(value => {
return getData(value);
}))
.pipe(tap(value => console.log(value)))
.pipe(catchError(err => {
console.error(err);
return of(null);
}))
.subscribe();
for(let i of [3 ,5 ,7 ,9 ,10, 11, 13, 15, 17]) {
subject.next(i);
}
上面的代码在运行的时候输出如下:
我使用getData
函数模拟http请求,假如http请求出错,如何不取消当前subject的订阅?即继续处理后续11, 13, 15, 17
这些数据,我使用了catchError
但是不生效。
目前已知的一个解决方法是把pipe
放到switchMap
里面,但是这样嵌套很不美观,求其他解决方式?
subject
.pipe(switchMap(value => {
return getData(value)
.pipe(tap(value => console.log(value)))
.pipe(catchError(err => {
console.error(err);
return of(null);
}))
}))
.subscribe();
https://stackblitz.com/edit/r...
你可以把
catchError
放到getData
中使用,这样就不会中断后面的后续的流了.