An Angular Http Interceptor For Each Api
Hello, I have 3 different apis for different services. Each API has you own Auth Token. I want to create 3 http interceptors, one for each api. I know create a httpInterceptor for
Solution 1:
You can use a single interceptor, and since in this one you have access to read the URL, you can create a function that depending on this uses a different token, for example:
intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
let token;
if (request.url.indexOf(PATH_ROUTE_ONE) !== -1) {
token = localStorage.getItem(TK1);
} elseif(request.url.indexOf(PATH_ROUTE_TWO) !== -1) {
token = localStorage.getItem(TK2);
} else {
token = localStorage.getItem(TK3);
}
if (token) {
request = request.clone({
setHeaders: {
authorization: `Bearer ${token}`,
},
});
}
return next.handle(request).pipe(
tap((res) => {
if (res instanceofHttpResponse) {
// TODO: Update token info
}
}),
catchError((err: HttpErrorResponse) =>throwError(err)),
);
}
If you want to use 3 paths you can do the same and you only read the URL to know if you apply it or let it continue long
intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
let token = localStorage.getItem(TK1)
if (request.url.indexOf(PATH_ROUTE_ONE) !== -1) {
request = request.clone({
setHeaders: {
authorization: `Bearer ${token}`,
},
});
}
return next.handle(request).pipe(
tap((res) => {
if (res instanceofHttpResponse) {
// TODO: Update token info
}
}),
catchError((err: HttpErrorResponse) =>throwError(err)),
);
}
Post a Comment for "An Angular Http Interceptor For Each Api"