【发布时间】:2023-11-17 16:41:01
【问题描述】:
我目前正在尝试使用 PrimeNG 9 messageService 和 Angular 8 HttpInterceptor 在我的应用程序中实现全局错误处理程序。我的代码如下:
app.component.html
//....
<p-toast key="notification" position="top-right"></p-toast>
app.module.ts
providers: [ ...
{
provide: HTTP_INTERCEPTORS,
useClass: ErrorInterceptor,
multi: true,
},
...
error-interceptor.interceptor.ts
import { Injectable, ɵConsole } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpErrorResponse } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { MessageService } from 'primeng/api';
import { Router } from '@angular/router';
@Injectable({
providedIn: 'root'
})
export class ErrorInterceptor implements HttpInterceptor {
constructor(
private messageService: MessageService,
private router: Router
) {}
public intercept(httpRequest: HttpRequest<any>, next: HttpHandler) : Observable<HttpEvent<any>> {
if (httpRequest.method !== 'GET')
return next.handle(httpRequest);
else {
return next.handle(httpRequest).pipe(
catchError( (err: HttpErrorResponse) => {
console.log(err)
this.messageService.add({
key: 'notification',
severity: 'error',
summary: 'Woops! There was an error!',
});
return throwError(err);
})
);
}
}
拦截器成功捕获错误并在控制台中打印出来。但是,toast 永远不会显示。我还指出我在其他组件中使用了 messageService 并且正确显示了 toast,它在拦截器中不起作用。
【问题讨论】:
-
你能添加一个stackblitz吗...我的添加中有同样的东西,它工作正常
-
@bubbles 你在使用 HttpInterceptor 和 PrimeNG messageService 吗?
-
@bubbles 您的应用程序是在 GitHub 上还是在其他开源文件夹上?我想看看代码来检查我的错误配置!
-
你可以在这里添加你的代码stackblitz.com我去看看
标签: angular primeng angular-http-interceptors