Angular - Ngrx - 在 http-status 0 处重试服务器请求
设置
- Angular 13.2.0
- Ngrx 13.0.2
- 后端:Spring Boot
目标
当后端未运行时,我想重试 url x 次。
到目前为止有效的
fetchEntities$ = createEffect(() =>
this.actions$.pipe(
ofType(DoctransActions.fetchEntities),
exhaustMap(action =>
this.http.get<DoctransResponse>(`${this.apiUrl}/some url`).pipe(
map(response => {
return action to set entities
}),
catchError((err) => {
return action for error
)
)
)
);
拦截器
@Injectable()
export class RetryInterceptor implements HttpInterceptor {
constructor(private store: Store<AppState>) {}
intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
return next.handle(request).pipe(
retryWhen(error =>
error.pipe(
concatMap((error, count) => {
if (count < environment.http.retry && environment.http.retryAtCodes.includes(error.status)) {
this.store.dispatch(retryFetch({errorRespone: error, retryCount: (count+1)}));
return of(error);
}
return throwError(error);
}),
delay(environment.http.delay)
)
)
)
}
}
retryFetch 操作为系统尝试连接的用户设置一个错误。
问题
有更好的方法吗?
解决方案
请参阅: Angular - ngrx - 持续从服务器获取数据的效果
EvenSource 会自动重新连接
Setup
- Angular 13.2.0
- Ngrx 13.0.2
- Backend: Spring Boot
Goal
When the backend is not running i want to retry the url x-times.
What works so far
fetchEntities$ = createEffect(() =>
this.actions$.pipe(
ofType(DoctransActions.fetchEntities),
exhaustMap(action =>
this.http.get<DoctransResponse>(`${this.apiUrl}/some url`).pipe(
map(response => {
return action to set entities
}),
catchError((err) => {
return action for error
)
)
)
);
Interceptor
@Injectable()
export class RetryInterceptor implements HttpInterceptor {
constructor(private store: Store<AppState>) {}
intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
return next.handle(request).pipe(
retryWhen(error =>
error.pipe(
concatMap((error, count) => {
if (count < environment.http.retry && environment.http.retryAtCodes.includes(error.status)) {
this.store.dispatch(retryFetch({errorRespone: error, retryCount: (count+1)}));
return of(error);
}
return throwError(error);
}),
delay(environment.http.delay)
)
)
)
}
}
The retryFetch Action sets an error for the user that the system is trying to connect.
Question
Is there a better way of doing this?
Solution
See: Angular - ngrx - Effect for continually getting data from server
EvenSource does automatic reconnecting
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这也好。
请参阅以下内容以获取更多灵感:
This is also fine.
See the following for more inspiration: