To handle multiple paths with different tokens, you can utilize a single interceptor in Angular. This interceptor allows you to access the URL and apply specific token logic based on the path. Here's an example implementation:
intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
let token;
if (request.url.indexOf(PATH_ROUTE_ONE) !== -1) {
token = localStorage.getItem(TK1);
} else if(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 instanceof HttpResponse) {
// TODO: Update token info
}
}),
catchError((err: HttpErrorResponse) => throwError(err)),
);
}
If you need to handle three different paths with unique tokens, you can extend this approach by adding additional conditions in the interceptor. By reading the URL, you can determine which token to use for each path.
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 instanceof HttpResponse) {
// TO-DO: Update token info
}
}),
catchError((err: HttpErrorResponse) => throwError(err)),
);
}