注入NotificationService后Angular HttpInterceptor失效问题排查
问题分析
拦截器注入NotificationService后完全不执行且无控制台报错,核心原因是**NotificationService依赖的ToastrService未被正确配置**。ngx-toastr要求必须在模块中导入ToastrModule并调用forRoot()完成初始化,否则ToastrService无法被注入,导致NotificationService实例化失败,进而ErrorInterceptor因依赖无法满足而无法被加载,最终拦截器不生效。
解决方案
步骤1:在AppModule中导入并配置ToastrModule
修改app.module.ts,添加ToastrModule的导入和初始化:
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { LayoutsModule} from "./layouts/layouts.module"; import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { ErrorInterceptor } from './core/helpers/error.interceptor'; // 导入ToastrModule import { ToastrModule } from 'ngx-toastr'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserAnimationsModule, HttpClientModule, BrowserModule, AppRoutingModule, LayoutsModule, // 初始化ToastrModule,可添加自定义配置 ToastrModule.forRoot({ positionClass: 'toast-top-right', timeOut: 5000 }) ], providers: [ { provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true } ], bootstrap: [AppComponent] }) export class AppModule { }
步骤2:验证依赖安装
确保已正确安装ngx-toastr及其依赖:
# 若未安装,执行以下命令 npm install ngx-toastr @angular/animations
可选:解决潜在循环依赖(若上述步骤无效)
若仍存在问题,可能是拦截器与服务间存在隐性循环依赖,可通过Injector延迟获取NotificationService,避免初始化时的依赖冲突:
修改error.interceptor.ts:
import { NotificationService, MessageType } from '../services/notification.service'; import { Injectable, Injector } from "@angular/core"; import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor, } from "@angular/common/http"; import { Observable, throwError } from "rxjs"; import { catchError } from "rxjs/operators"; @Injectable({ providedIn: "root", }) export class ErrorInterceptor implements HttpInterceptor { private notificationService: NotificationService; constructor(private injector: Injector) {} intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { // 延迟获取服务实例 this.notificationService = this.injector.get(NotificationService); return next.handle(request).pipe( catchError((err) => { console.log("Response Error: ",err); if (err.status === 401) { // to do: auto logout if 401 response returned from api } else { this.notificationService.showActionNotification( 'Titel', 'This document is currently DRAFT ONLY, please contact created user or a system administrator for further details', MessageType.Error ); } const error = err.error.message || err.statusText; return throwError(() => error); }) ); } }
验证
重新启动应用,触发HTTP错误请求,此时拦截器应正常执行并弹出错误提示。
内容的提问来源于stack exchange,提问作者Aruna101
相关产品推荐
相关产品推荐

