我目前正在尝试使用 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,
},
...
错误拦截器.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);
})
);
}
}
拦截器成功捕获错误并将其打印在控制台中。但是,吐司永远不会显示。我还指出,我在其他组件中使用了 messageService 并且 toast 正确显示,它只是在拦截器中不起作用。
您已声明并要求在所需位置领取烤面包机吗? 例如。在 x-page.module 中,您需要声明烤面包机/函数/无论在哪里,并在 x-page.ts 中调用它
添加到app.module中的“deps”数组
{
provide: HTTP_INTERCEPTORS,
useClass: ErrorInterceptor,
multi: true,
deps: [AuthService, MessageService],
}
如果有人仍在 Angular 17 中寻找此功能,只需在 ApplicationConfig 中添加 MessageService