Angular 2 - Inject authorization token before each Http request

僤鯓⒐⒋嵵緔 提交于 2019-12-24 01:14:29

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/39373645/angular-2-inject-authorization-token-before-each-http-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!