上下文: 使用 Angular 9。我正在尝试等待后端可以接收请求。同时它不是,有一个进度条加载。
问题:后台还未可用时,订阅立即失败,进入方法.subscribe()
的(error)回调函数,with类似于 http://localhost:5555/api/info: 504 Gateway Timeout 的 Http 失败响应
我做了一些研究,我发现的示例修改了存在 httpClient.get
的服务类,以重试 x 次请求,但我不能这样做,因为ts 服务是自动生成的。
我的第一个想法是使用 while() 循环和一个标志,因此每次执行 (error) 时,标志都将为 false,然后重试订阅。但它会导致内存泄漏。
checkIfBackendAvailable() {
var backendAvailable = false;
while(!backendAvailable){
let subscription = this.infoService.getInfo().subscribe(
(info) => {
if (info) {
backendAvailable = true;
this.progressBarValue = 100
// do somethings
}
}
,
(error) => {
clearTimeout(this.infoTimeOut);
this.showMessage("back-end not available");
this.stopLoadingBar();
//do somethings
}
);
}
this.infoTimeOut = setTimeout(() => {
if (!backendAvailable) {
subscription.unsubscribe()
this.showMessage("error");
this.stopLoadingBar();
}
}, 120000);
}
最佳答案
只要您的服务函数返回 Observable
,您仍然可以使用 retry
或 retryWhen
可观察运算符。
使用重试
:
this.infoService.getInfo()
.pipe(
retry(3), // you retry 3 times
delay(1000) // each retry will start after 1 second,
)
.subscribe(res => {
// success
})
使用retryWhen
:
this.infoService.getInfo()
.pipe(
retryWhen(errors => errors.pipe(
// define conditions for retrying with some of observable operators
)),
)
.subscribe(res => {
// success
})
关于angular - 在 Angular 9 中失败时如何重试订阅?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63113192/