I wanted to fetch new access token before making api request. This token will append to previous api call in interceptor. So how to make another api call in angular interceptor?
import { Injectable } from '@angular/core';
import {
HttpRequest,
HttpHandler,
HttpEvent,
HttpInterceptor
} from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable()
export class TokenInterceptor implements HttpInterceptor {
constructor() {}
intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
// To do for validating token
request = request.clone({
setHeaders: {
Authorization: 'Bearer '+ localStorage.getItem('access_token')
}
});
return next.handle(request);
}
}
Angular interceptor provides a way to call another api call before making actual api call. Before proceeding further you need to import following
import { HttpClient } from '@angular/common/http';
import { catchError, switchMap, tap } from 'rxjs/operators';
In above tap is being used to get response of intermediate call where as switchMap is used for calling actual api call.
So, it has following steps to do job.
so, the code would look like below.
constructor(private http: HttpClient) {}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return this.http.get(`https://<fetch access token URL>`, {observe: 'response'}).pipe(
tap(response => {
localStorage.setItem("access_token", response.headers.get('access_token'));
}),
switchMap(() => {
request = request.clone({
setHeaders: {
Authorization: `Bearer ${localStorage.getItem('access_token')}`
}
});
return next.handle(request);
})
);
});