Генерация refreshToken перед запросом, если это необходимо
export class HttpRequestInterceptor implements HttpInterceptor {
constructor(private router: Router, private service: AuthService) { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<any> {
return from(this.tokenHandler(request)).pipe(mergeMap((req: HttpRequest<any>) => {
return next.handle(req).pipe(catchError(err => {
if ([401].indexOf(err.status) != -1) {
// auto logout if 401 response returned from api
}
else {
throw err;
}
return EMPTY;
}));
}));
}
private async tokenHandler(request: HttpRequest<any>): Promise<HttpRequest<any>> {
if (request.url.indexOf("REFRESHTOKEN_URL") == -1) {
await this.service.GenerateNewTokenIfNeed(); //Important this function would be async and put httpClient call to ToPromise() and await it. Save token somewhere and get from there to #token# place
}
else {
//RefreshTokenRequest
}
const authReq = request.clone({
setHeaders: {
Authorization: "Bearer #token#"
},
});
return authReq;
}