How to identify specific request came at HTTP Interceptor using Angular 5?
You can check the if the req.url
is equal to the path you want to exclude like below:
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// put this before your current code
if (req.url.indexOf('/* the api path you want to exclude*/') === -1) {
return next.handle(req);
}
// do your stuff here.
return next.handle(req);
}
You can add a condition based on your req.url
like this:
intercept (req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if (!req.url.includes('/some/url-to-be-escaped') {
// Do nothing
return next.handle(req);
}
this.loadingIndicatorService.showLoader();
this.customAuthorizationHeader();
const apiRequest = req.clone({headers:this.headers});
// The rest of your stuff
return next.handle(req);
}
Hope it helps.
We can do in above ways like check for URL in interceptor itself,but later if we modify the URL like login to sign in,and signup to join or so.This way of implementation will cause side effect.Or overload the interceptor if we have multiple type of logins/un-authenticated pages.
So i suggest We can use an user defined "InterceptorSkipHeader" from login/signup kind of services
unAuthenticatedAPI(someUrl){
const headers = new HttpHeaders().set(InterceptorSkipHeader, '');
this.httpClient.get<ResponseType>(someUrl, { headers });
}
And in interceptor you can just check for request with these header and exclude authenticantion
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if (!req.headers.has(InterceptorSkipHeader)) {
// set token here.
const apiRequest = req.clone({headers:this.headers})
}
return next.handle(req);
}