Angular interceptor exclude specific urls
Update from Angular 12, use "context", see this SO
I suggest that, in spite of check the request, you can use the header to add a "skip" property, if the header has the skip property, simple return the reqs
export class CustomInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if (req.headers.get("skip"))
return next.handle(req);
....
}
}
And you make all the calls you need "skip" the interceptor like
this.http.get(url, {headers:{skip:"true"});
after checking for req.headers.get("skip")
as Eliseo suggested, I'd recommend removing this header from request since it's Angular-related only and it should not be transmitted to the API (actually it can cause issues)
const skipIntercept = request.headers.has('skip');
if (skipIntercept) {
request = request.clone({
headers: request.headers.delete('skip')
});
}
What I wound up doing is having an array of urls (in Regex Format) that I did not want to be used in the interceptor like so:
import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable()
export class AddCustomHeadersInterceptor implements HttpInterceptor {
urlsToNotUse: Array<string>;
constructor(
) {
this.urlsToNotUse= [
'myController1/myAction1/.+',
'myController1/myAction2/.+',
'myController1/myAction3'
];
}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if (this.isValidRequestForInterceptor(request.url)) {
let modifiedRequest = request.clone({
setHeaders: {
//DO WORK HERE
}
});
return next.handle(modifiedRequest);
}
return next.handle(request);
}
private isValidRequestForInterceptor(requestUrl: string): boolean {
let positionIndicator: string = 'api/';
let position = requestUrl.indexOf(positionIndicator);
if (position > 0) {
let destination: string = requestUrl.substr(position + positionIndicator.length);
for (let address of this.urlsToNotUse) {
if (new RegExp(address).test(destination)) {
return false;
}
}
}
return true;
}
}