2

I need to check that my token is not expired before I send every HTTP request. I'm trying to make injection using Http Interceptor like this:

class HttpInterceptor extends Http {

  constructor(backend: ConnectionBackend, defaultOptions: RequestOptions, private _router: Router) {
    super(backend, defaultOptions);
  }

  get(url: string, options?: RequestOptionsArgs): Observable<Response> {
    const keycloak$: Observable = KeycloakService.updateToken();

    return keycloak$.map((options) => {
      return super.get(url, this.getRequestOptionArgs(options));
    });
    // -> Observable<Observable<Response>>
  }

  getRequestOptionArgs(options?: RequestOptionsArgs) : RequestOptionsArgs {
    if (options == null) {
        options = new RequestOptions();
    }
    if (options.headers == null) {
        options.headers = new Headers();
    }
    options.headers.append('Content-Type', 'application/json');

    return options;
  }
}

How I can implement Observable dependency. KeycloakService.updateToken() returns another Observable, so I need to wait for response and then add Authorization header. I will be grateful for any tips.

Nowy
  • 63
  • 5
  • How is your `KeycloakService.updateToken()` returning an Observable? The code I got from Keycloak's website returns a Promise. Could you point me to where I can find the Observable version of the code? Thanks! – FilmiHero Nov 09 '16 at 18:41

1 Answers1

3

Use switchMap to wait for the observable returned by super.get() to resolve before emitting the response

Replace

return keycloak$.map((options) => {
  return super.get(url, this.getRequestOptionArgs(options));
});

With

return keycloak$.switchMap(
    options => super.get(url, this.getRequestOptionArgs(options))
);

Examples

I would also change:

if (options == null) {
    options = new RequestOptions();
}
if (options.headers == null) {
    options.headers = new Headers();
}

With:

if(!options) options = new RequestOptions();
if(!options.headers) options.headers = new Headers();

In order to catch undefined as well as null options

BeetleJuice
  • 39,516
  • 19
  • 105
  • 165
  • for me the same method is not working. can you please help me understand a bit more. i posted a question with details at https://stackoverflow.com/questions/47872897/angular-getting-authorization-token-asynchronously-before-http-calls – gaurang171 Dec 18 '17 at 16:50