angular - 在 RxJS 中捕获不同的错误
问题描述
我有一个 Angular 的 HTTP 拦截器。应用程序使用 RxJS 计时器发送请求(短轮询)。它每 5 秒发送大约 10 个请求。我想使用拦截器来处理 502-504 状态码。我知道如何捕捉错误,但问题是轮询。
一旦我发送 10 个请求,我几乎同时收到 10 个错误。我想distinctUntilChanged()
或至少take(1)
以某种方式,但这两件事不能与catchError()
.
export class ErrorInterceptor implements HttpInterceptor {
constructor(private readonly store: Store<AppState>) { }
intercept(request: HttpRequest<string>, next: HttpHandler): Observable<HttpEvent<string>> {
const errorCodes = [502, 503, 504];
return next.handle(request).pipe(
// take(1),
// distinctUntilChanged(), // both lines not working, because error is thrown earlier
catchError(err => {
if (errorCodes.includes(err.status)) this.store.dispatch(connectionLost());
return throwError(err);
})
);
}
}
我知道我可以发送一个关于错误的新操作并使用distinctUntilChanged
它的效果。但是我会在 Redux DevTools 中分派这个动作 10 次。我想避免这种情况。
有任何想法吗?
解决方案
您可以使用materialize()
和dematerialize()
。使用materialize()
您可以抑制传入的错误并将它们作为错误通知(不是错误本身)发送,然后您可以提供自定义compare
fn 到distinctUntilChanged
.
return next.handle(request).pipe(
/* ... */
materialize(), // Convert into notification
distinctUntilChanged(yourCustomFn),
/* ... */
dematerialize() // Get back the `original value`
/* ... */
);
推荐阅读
- typescript - 类型缺少以下属性
- mysql - 如何在没有空输出的情况下通过多选联合所有和分组?
- regex - 如何处理字符串中的自定义标签并记录有关格式的信息
- google-apps-script - 数据更改时自动对行进行排序
- r - 按日期和变量对数据框进行排序
- c# - 在未激活 .NET 3.5 Windows 功能的情况下运行 C# exe
- react-native - 如何在 react-native viewpager 中使用动画更改背景颜色?
- c# - 用粗体标签在短语周围附加单词
- javascript - 并行异步/等待操作
- apache - .htaccess -> Nginx 配置