angularangular-servicesangular-http-interceptors

Angular service not working when injected in to HttpInterceptor


I'm trying to create a HttpInterceptor to catch any errors in http responses. My HttpInterceptor catch errors as expected. But when i use "ngx-toastr" to display error message using a NotificationService, the HttpInterceptor is not executing at all.

app.module.ts Code:

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, HttpClient, HTTP_INTERCEPTORS  } from '@angular/common/http';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { ErrorInterceptor } from './core/helpers/error.interceptor';

@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserAnimationsModule,
HttpClientModule,
BrowserModule,
AppRoutingModule,
LayoutsModule
],
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true }
],
bootstrap: [AppComponent]
})
export class AppModule { }

error.interceptor Code:

import { NotificationService, MessageType } from '../services/notification.service';
import { Injectable } 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 {
  
  constructor(private notificationService: NotificationService) {}

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    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);
      })
    );
  }
}

notification.service.ts Code:

import { Injectable } from "@angular/core";
import { ToastrService } from "ngx-toastr";

@Injectable({providedIn: "root"})

export class NotificationService {

  constructor(private toastr: ToastrService) {}

  showActionNotification(
    title: string,
    message: string,
    type: MessageType
  ) {
    if (type === MessageType.Success) {
      this.toastr.success(message, title);
    } else if (type === MessageType.Info) {
      this.toastr.info(message, title);
    } else if (type === MessageType.Warning) {
      this.toastr.warning(message, title);
    } else if (type === MessageType.Error) {
      this.toastr.error(message, title);
    } else {
      this.toastr.info(message, title);
    }
  }
}

export enum MessageType {
  Error,
  Info,
  Warning,
  Success
}

When i remove NotificationService from ErrorInterceptor, ErrorInterceptor can catch errors. If NotificationService is injected, it doesn't catch any error and there also no any console error in browser.

Tried above code in Angular 13. But unable to figure-out the cause as there is no any console error.


Solution

  • your interceptor looks fine. Maybe your notification service doesn't work. Check that you imported ToastrModule in *.module.ts

    imports:[
    ToastrModule.forRoot()
    ...
    ]