Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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));   }); } 
like image 937
Haneep CR Avatar asked Apr 10 '18 06:04

Haneep CR


People also ask

Can I have multiple HTTP interceptors in angular?

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 .

What is Http_interceptors in angular?

HTTP_INTERCEPTORSlinkA multi-provider token that represents the array of registered HttpInterceptor objects.

How do you create an angular interceptor?

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.


2 Answers

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); 

}

like image 82
DragoRaptor Avatar answered Sep 18 '22 10:09

DragoRaptor


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.

like image 36
Fussel Avatar answered Sep 19 '22 10:09

Fussel