'Angular Authz Interceptor not triggering

I'm making API calls to different server other than my own backend. This third party API requires authentication. I tried with an Interceptor

import { Injectable } from '@angular/core';
import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpInterceptor,
  HttpClient
} from '@angular/common/http';
import { Observable } from 'rxjs';


export interface AuthResponse {
  UserName: any;
  AuthToken: any;
}

@Injectable()
export class AuthInterceptor implements HttpInterceptor {

  api = 'https://api.example.com';
  username = 'demo';
  password = 'demo';

  constructor(
    private http: HttpClient
  ) {}

  getToken = () => {
    return this.http.post<AuthResponse>(`${this.api}/authenticate`, {username: this.username, password: this.password})
  }

  intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
    const authReq = request.clone({
      headers: request.headers.set('Authorization', `Bearer: ${this.getToken().subscribe(res => res.AuthToken)}`).set('Content-Type', 'application/json')
    });
    return next.handle(authReq);
  }
}

In the module I added

  providers: [
    ServiceThatMakesHTTPRequests,
    {
      provide : HTTP_INTERCEPTORS,
      useClass: AuthInterceptor,
      multi   : true
    }
  ]

Apparently it's not getting triggered.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source