0
votes

I create new interceptors name HttpInterceptor. Here is the sample code:

import { Injectable } from '@angular/core';
import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpInterceptor,
  HttpResponse,
  HttpErrorResponse,
} from '@angular/common/http';

import { Observable } from 'rxjs';

import { ErrorHandler } from './error_handler';

@Injectable()
export class RequestInterceptor implements HttpInterceptor {

  constructor(
    public errorHandler: ErrorHandler,
  ) { }

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    return next.handle(request).do((event: HttpEvent<any>) => { }, (err: any) => {
      if (err instanceof HttpErrorResponse) {
        this.errorHandler.handleError(err);
      }
    });
  }
}

i have added providers in app.module.ts

providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: RequestInterceptor,
      multi: true,
    }
  ]

I got this error.

Error: StaticInjectorError(AppModule)[InjectionToken HTTP_INTERCEPTORS -> ErrorHandler]: StaticInjectorError(Platform: core)[InjectionToken HTTP_INTERCEPTORS -> ErrorHandler]: NullInjectorError: No provider for ErrorHandler!

My code in Angular 7. Please help me.

1
if is Angular 7 is Rxjs 6, so "do" is replace by "tap", More: you must change your imports github.com/ReactiveX/rxjs/blob/master/docs_app/content/guide/v6/… and use pipe github.com/ReactiveX/rxjs/blob/master/docs_app/content/guide/v6/… - Eliseo

1 Answers

0
votes

Add ErrorHandler in root, You can not use any service directly without adding in providers, So after angular 6+ version they introduce new syntax that you can add in root of the module.

So you can use that service entire application.

For Example,

@Injectable({
    providedIn: 'root'
})
export class ErrorHandler{
}

also add RequestInterceptor in root of the module,

@Injectable({
        providedIn: 'root'
})
export class RequestInterceptor implements HttpInterceptor{
}