Search code examples
angulartypescriptinterceptorangular-httpclient

How to exclude some services like login, register from interceptor Angular 5, HttpClient


i wanted to exclude some services using interceptor.

app.module.js

providers: [
    UserService,
    RolesService,
    {
        provide: HTTP_INTERCEPTORS,
        useClass: TokenInterceptor,
        multi: true
      },
],

Login.service.ts

return this.httpClient.post(this.appUrl + '/oauth/token', body.toString(), { headers, observe: 'response' })
.map((res: Response) => {
  const response = res.body;
  this.storeToken(response);
  return response;
})
.catch((error: any) => {
  ErrorLogService.logError(error);
  return Observable.throw(new Error(error.status));
  });
}

Solution

  • To give this an answer not only in comments as requested ;-)

    To exclude some services (or even the same services used in different components) from an interceptor it's best to split your application into modules and provide the interceptor only in modules where it's needed. For example after logging in or inside of an admin area.

    The interceptor may be even provided for single components using the @Component declaration's providers property.