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)); }); }
So how can I add multiple interceptors? Http doesn't allow to have more than one custom implementation. But as @estus mentioned the Angular team has added a new HttpClient service recently (release 4.3) which supports multiple interceptors concept. You don't need to extend the HttpClient as you do with the old Http .
HTTP_INTERCEPTORSlinkA multi-provider token that represents the array of registered HttpInterceptor objects.
The first step is to build the interceptor. To do this, create an injectable class that implements HttpInterceptor. Any interceptor we want to create needs to implement the HttpInterceptor interface. This means that our new class should have a method called intercept with parameters HttpRequest and HttpHandler.
Although #Fussel's answer (above) works, it's often not good practice to include the interceptor service in every component module. It's counter intuitive and counter productive. We want the interceptor in one place and work for all http requests. One way is to exclude the header binding in the intercept() function based on the url.
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { const re = /login/gi; // Exclude interceptor for login request: if (req.url.search(re) === -1 ) { req = req.clone({ setHeaders: { Authorization: `Bearer ${localStorage.getItem('authToken')}` } }); } return next.handle(req);
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With