Answer the question
In order to leave comments, you need to log in
Angular interceptor not working?
interceptor not working in angular
public intercept(
request: HttpRequest<any>,
next: HttpHandler,
): Observable<HttpEvent<any>> {
return this.authService.getAuthorizationToken().pipe(
tap(token => this.authService.token = token),
mergeMap(token => {
console.log('this.auth.newAccessToken:', this.authService.token);
const newRequest = request.clone({
setHeaders: {
Authorization: `Bearer ${token}`
}
});
console.log('newRequest.headers.get("Authorization"):', newRequest.headers.get('Authorization'));
return next.handle(newRequest);
})
);
}
public getAuthorizationToken(): Observable<IdentityToken> {
const publicId: string = this.getPublicId();
return this.apiBaseService
.get<IdentityToken>(`identity/token?publicId=${publicId}`)
}
Answer the question
In order to leave comments, you need to log in
Do you want to go to the backend for a token before each request, or what? It's unclear what's going on here.
My token interceptor is made as simple as possible.
export class AuthInterceptor implements HttpInterceptor {
constructor(
private authState: AuthState,
) { }
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle( req.clone({
headers: req.headers.set('Authorization', `Bearer ${this.authState.getValue().token}`),
}));
}
}
this.authService.getAuthorizationToken().pipe(
take(1),
switchMap(token => next.handle(this.makeNewRequest(token))
)
tap(token => this.authService.token = token),
should not be in the interceptor at all.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question