Issue
I am writing interceptors such that I don’t have to handle the headers in every service calling my web api. The problem with this is that 99% of my calls require 1 specific set of headers, but the other 1% only require 1 of the headers and will not work with the others present. With this being known my idea is to make 2 interceptors, the first will add the 1 header that they all use and the second will add the rest of the headers, with the second excluding the 1%.
The following is how I am going about excluding the 1%, which works, but I want to see if there is a better way of going about this:
intercept(request: HttpRequest<any>, next:HttpHandler: Observable<HttpEvent<any>> {
let position = request.url.indexOf('api/');
if (position > 0){
let destination: string = request.url.substr(position + 4);
let matchFound: boolean = false;
for (let address of this.addressesToUse){
if (new RegExp(address).test(destination)){
matchFound = true;
break;
}
}
if (!matchFound){
...DO WORK to add the headers
}
}
Solution
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;
}
}