Typescript 完成retryWhen后RxJS返回错误
我想在Typescript 完成retryWhen后RxJS返回错误,typescript,rxjs,Typescript,Rxjs,我想在retryWhen完成后返回错误。下面是代码示例: consthttpget=(d,res)=>{ 返回rxjs.of(res.pipe)(rxjs.operators.delay(d)); }; 常量重复=()=>{ 返回httpGet(1000,假)。管道( 点击(()=>console.log(“来自重复的响应”), rxjs.operators.flatMap(res=>{ 如果(res==false){ //由于响应无效而引发错误 返回rxjs.throwerr(“重复中的无效
retryWhen
完成后返回错误。下面是代码示例:
consthttpget=(d,res)=>{
返回rxjs.of(res.pipe)(rxjs.operators.delay(d));
};
常量重复=()=>{
返回httpGet(1000,假)。管道(
点击(()=>console.log(“来自重复的响应”),
rxjs.operators.flatMap(res=>{
如果(res==false){
//由于响应无效而引发错误
返回rxjs.throwerr(“重复中的无效响应”);
}
返回rxjs.of(res);
}),
rxjs.operators.retryWhen(err=>{
//由于响应无效,请重试相同的httpGet调用
返回错误管道(
rxjs.operators.flatMap(e=>{
//延迟执行下一个httpGet调用
返回rxjs.定时器(1000);
}),
//仅重试httpGet调用3次
rxjs.operators.take(3)
);
})
);
};
const execute=()=>{
返回httpGet(1000,假)。管道(
点击(()=>console.log(“来自执行的响应”),
rxjs.operators.switchMap(res=>{
//如果res为false,请等待1秒并执行repeat()
如果(res==false){
返回rxjs.timer(1000.pipe)(rxjs.operators.concatMapTo(repeat());
}
返回rxjs.of(res);
})
);
};
//开始执行
执行()。订阅(
r=>console.log(“响应:”,r),
err=>console.error(“error:,err),
()=>console.log(“已完成”)
);代码>
您可以在最后一次执行时抛出
rxjs.operators.retryWhen(err => {
let count=0;
// Retry same httpGet call due to invalid response
return err.pipe(
rxjs.operators.flatMap(e => {
++count;
console.log(count)
// Delay execution of next httpGet call
if(count===3) return rxjs.throwError(e);
return rxjs.timer(1000);
}),
// Retry httpGet call only 3 times
rxjs.operators.take(3)
);
})
);
我允许我自己用一个片段提供您的问题的一部分,并且我删除了Angular标记(因为它只与RxJS相关,即使您使用Angular)。如果你觉得这不公平,就告诉我,我将回滚更改。这个解决方案非常有效。此解决方案是否有更精确/优雅的版本?在err.pipe中附加扫描运算符以存储count还有一个count()运算符可供使用