Home > Software design >  How to use NzMessageService in HttpInterceptor
How to use NzMessageService in HttpInterceptor

Time:12-14

When I use NzMessageService in HttpInterceptor in angular I get the following error:

login.component.ts:116 NullInjectorError: R3InjectorError(Y)[InjectionToken HTTP_INTERCEPTORS -> [object Object] -> he -> rt -> rt -> rt]: 
  NullInjectorError: No provider for rt!
    at Mu.get (core.mjs:8177:27)
    at Kd.get (core.mjs:8604:33)
    at Kd.get (core.mjs:8604:33)
    at Kd.get (core.mjs:8604:33)
    at Tc (core.mjs:4761:33)
    at Object.Wo (core.mjs:4765:42)
    at he.ɵfac [as factory] (ng-zorro-antd-message.mjs:119:107)
    at Kd.hydrate (core.mjs:8705:35)
    at Kd.get (core.mjs:8593:33)
    at Tc (core.mjs:4761:33)

my interceptor.service.ts code is:

@Injectable()
export class InterceptorService implements HttpInterceptor {
  constructor(private message: NzMessageService) {
  }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(req).pipe(catchError((err) => {
      this.message.create("error", "error message", {
        nzDuration: 4000
      });
      return throwError(err);
    }));
  }
}

my app.module.ts nearly is:

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    NzMessageServiceModule
  ],
  providers: [
    NzMessageService,
    {provide: HTTP_INTERCEPTORS, useClass: InterceptorService, deps: [NzMessageService], multi: true},
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

How can I fix this problem?

CodePudding user response:

You have to import the following module in your app.module.ts, and no need for NzMessageServiceModule and NzMessageService.

import { NzMessageModule } from 'ng-zorro-antd/message';
  • Related