我想继续重试对服务器的调用(看看它是否返回 true)。
在我的服务中,我创建了一个 http 调用,如果能够检索值,则返回 true;如果无法检索值,则返回 false(从而出现错误)。
public retryServerCheck(): Observable<boolean> {
return this._httpClient.get<boolean>(this.baseUrl + 'ServerCheck')
.pipe(
map(() => true),
catchError(() => of(false)
));
}
在我的组件中,我想重试此操作,直到返回 true
,这就是我的问题。
this._serverService.retryServerCheck()
.subscribe(
(isOnline) => {
if (isOnline) {
this._helperServer.navigateToComponent('Login', undefined, 0);
console.log('online');
} else {
this.lastRetry = 'A little later...';
console.log('offline');
}
}
);
我尝试在订阅前面添加一个管道,但没有成功
this._serverService.retryServerCheck()
.pipe(
retry(10),
delay(100)
).subscribe(
(isOnline) => {
if (isOnline) {
this._helperServer.navigateToComponent('Login', undefined, 0);
console.log('online');
} else {
this.lastRetry = 'A little later...';
console.log('offline');
}
}
);
我能够在我的服务中进行重试,但随后我无法在我的组件中对其使用react
public retryServerCheck(): Observable<boolean | HttpError> {
return this._httpClient.get<boolean>(this.baseUrl + 'ServerCheck')
.pipe(
retryWhen(errors => errors.pipe(delay(500))),
catchError(err => {
return this._helperService.handelHttpError(err);
})
);
}
最佳答案
catchError
和 retryWhen
都会抑制流上的错误。所以在组件中错误已经被处理了。
尝试让 retryWhen
负责处理重试次数
// service
public retryServerCheck() {
return this._httpClient.get(this.baseUrl + 'ServerCheck').pipe(
retryWhen(error$ => error$.pipe(
take(10), // <-- number of retries
delay(500),
concat(
/* either throw your own error */
throwError('no more retries left')
/* or to pass original error -- use `NEVER` */
// NEVER
)
))
)
}
// component
this._serverService.retryServerCheck()
.subscribe({
next: (result) => {
// succeeded
},
error: (error)=> {
// failed
}
});
或添加 expand
到组件 - 当流上有 false
时重试。
关于javascript - 结果为 false 时重试订阅,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55412235/