Angular的HttpInterceptor中注入ngx-toastr服务报错如何解决
问题根因
你遇到的报错核心原因是ngx-toastr版本和Angular版本不兼容,同时可能存在配置错误、执行上下文不正确的问题,对应解决方法如下:
解决步骤
1. 版本适配(优先级最高)
ngx-toastr的大版本和Angular大版本是严格对应的:
- ngx-toastr@14.x 仅支持Angular 14.x
- Angular 12.x 对应的适配版本为
ngx-toastr@12.x
先卸载当前版本,安装适配版本:
npm uninstall ngx-toastr npm install ngx-toastr@12.1.1
同时请确认你的@angular/animations依赖版本和Angular核心版本一致,同为12.x系列。
2. 检查根模块配置
确保你在AppModule根模块中正确导入了依赖模块,不能在子模块/共享模块/懒加载模块中导入ToastrModule.forRoot():
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { ToastrModule } from 'ngx-toastr'; import { HTTP_INTERCEPTORS } from '@angular/common/http'; import { ToastrInterceptor } from './toastr.interceptor'; @NgModule({ imports: [ BrowserModule, BrowserAnimationsModule, // 必须在根模块调用forRoot初始化 ToastrModule.forRoot({ // 可自定义配置,比如位置、持续时间等 positionClass: 'toast-top-right', timeOut: 3000 }) ], providers: [ // 正确注册拦截器 { provide: HTTP_INTERCEPTORS, useClass: ToastrInterceptor, multi: true } ], bootstrap: [AppComponent] }) export class AppModule { }
3. 修复拦截器执行上下文
如果版本适配后仍存在报错,是因为拦截器的错误回调可能在Angular的变更检测区域外执行,导致无法获取应用实例,需要用NgZone包裹toast调用,修改你的拦截器代码:
import { Injectable, NgZone } from '@angular/core'; import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpErrorResponse } from '@angular/common/http'; import { Observable, throwError } from 'rxjs'; import { catchError } from 'rxjs/operators'; import { ToastrService } from 'ngx-toastr'; import { ERROR_MESSAGES } from 'src/app/utils/config/modal-settings'; @Injectable() export class ToastrInterceptor implements HttpInterceptor { // 注入NgZone constructor(private toastrService: ToastrService, private ngZone: NgZone) { } intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { return next.handle(req).pipe( catchError((error: HttpErrorResponse) => { console.error(error); let msg; if (error?.error?.message !== undefined) msg = error.error.message; else msg = ERROR_MESSAGES[error.status] || ERROR_MESSAGES[0]; // 用ngZone.run包裹确保在Angular上下文中执行 this.ngZone.run(() => { this.toastrService.error(msg); }) console.log("ERROR MESSAGE", msg); return throwError(error); }) ); } }
内容的提问来源于stack exchange,提问作者user3673449
相关产品推荐
相关产品推荐

