I have built an error interceptor in my first Angular application which is all new for me. The interceptor tries to refresh a Firebase authorization token when a 401
response code occures. Therefore I have written the following code:
@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
constructor(private authService: AuthService, private alertService: AlertService) { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request).pipe(
catchError(err => {
if (err.status === 401) {
let user = localStorage.getItem('currentUser');
if (!user) {
this.logout(false);
return throwError(err.error);
}
let currentUser = JSON.parse(user);
if (!currentUser || !currentUser.stsTokenManager || !currentUser.stsTokenManager.accessToken) {
this.logout(false);
return throwError(err.error);
}
const reference = this;
this.authService.getToken(currentUser, true).then(t => {
// How do I await and return this properly?
return reference.updateTokenAndRetry(request, next, currentUser, t);
}); // Get token and refresh
}
this.alertService.showAlert({
text: 'Fout tijdens het verzenden van het verzoek',
});
return throwError(err.error);
})
);
}
updateTokenAndRetry(request: HttpRequest<any>, next: HttpHandler, currentUser: any, token: string): Observable<HttpEvent<any>> {
// Update local stored user
currentUser.stsTokenManager.accessToken = token;
localStorage.setItem('currentUser', JSON.stringify(currentUser));
// Add the new token to the request
request = request.clone({
setHeaders: {
Authorization: token,
},
});
return next.handle(request);
}
The token gets refreshed fine. However the network call is not being executed after the refresh, which reference.updateTokenAndRetry(request, next, currentUser, t);
should do.
I assume the reason for this, is that this.authService.getToken(currentUser, true)
returns a Promise
(this is the Firebase plugin and can't be changed). I want to return return reference.updateTokenAndRetry(request, next, currentUser, t);
but this is not possible since it's in an async function block.
How can I await or return the next network call? I can't make the intercept
function async
. I am pretty stuck at this point.