我已经在我的角度项目中添加了一个http错误拦截器。
代码来自此示例:https://medium.com/@satyapriyamishra111/angular-error-interceptor-4b102f938065
如果接收到错误,我想显示一条祝酒消息,但是在某些情况下,我会多次遇到相同的错误,并且祝酒消息也会多次显示。
我尝试添加一个debounceTime:
return next.handle(request)
.pipe(debounceTime(1000),
catchError((error: HttpErrorResponse) => {
let errorMsg = '';
if (error.error instanceof ErrorEvent) {
console.log('this is client side error');
//show toast
}
else {
console.log('this is server side error');
errorMsg = `Error Code: ${error.status}, Message: ${error.message}`;
}
console.log(errorMsg);
return throwError(errorMsg);
})
但是吐司消息仍然显示多次。
答案 0 :(得分:0)
我认为debounceTime
仅在没有错误的情况下才会发生(在愉快的路上)。尝试在debounceTime
的末尾添加throwError
。
return next.handle(request)
.pipe( // remove debounceTime from here
catchError((error: HttpErrorResponse) => {
let errorMsg = '';
if (error.error instanceof ErrorEvent) {
console.log('this is client side error');
//show toast
}
else {
console.log('this is server side error');
errorMsg = `Error Code: ${error.status}, Message: ${error.message}`;
}
console.log(errorMsg);
return throwError(errorMsg).pipe(debounceTime(1000)); // add debounceTime here
});
答案 1 :(得分:0)
debounceTime只会增加一个延迟,但仍会到达处理程序。您是否尝试过Take操作符仅使用第一个发出的值来处理?
return next.handle(request)
.pipe(take(1), catchError((error: HttpErrorResponse) => {
let errorMsg = '';
if (error.error instanceof ErrorEvent) {
console.log('this is client side error');
//show toast
}
else {
console.log('this is server side error');
errorMsg = `Error Code: ${error.status}, Message: ${error.message}`;
}
console.log(errorMsg);
return throwError(errorMsg);
})
答案 2 :(得分:0)
感谢帮助人员,但答案对我没有用。 但是我找到了可行的解决方案:
export class HttpErrorInterceptor implements HttpInterceptor {
private errorSubject = new Subject<void>();
private error$ =
this.unreachableErrorSubject.asObservable().pipe(debounceTime(500));
constructor() {
this.error$.subscribe(()=>showToast));
}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request)
.pipe(
catchError((error: HttpErrorResponse) => {
let errorMsg = '';
if (error.error instanceof ErrorEvent) {
console.log('this is client side error');
this.errorSubject.next();
}
else {
console.log('this is server side error');
errorMsg = `Error Code: ${error.status}, Message: ${error.message}`;
}
console.log(errorMsg);
return throwError(errorMsg);
})
)
}
}