prolina2021-02-17 11:15:55
prolina, 2021-02-17 11:15:55

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

Console output will never work

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Anton Shvets, 2021-02-17

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 {
    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}`),

those. only a token is taken from the service, without unnecessary subscriptions and requests.
The first token is obtained from the request at the start of the application, updated in the requests themselves.
If there is no synchronous getter, then you need to do
  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 question

Ask a Question

731 491 924 answers to any question