Angular 2 - 在每个 Http 请求之前注入授权令牌

Angular 2 - Inject authorization token before each Http request

我需要在发送每个 HTTP 请求之前检查我的令牌是否过期。我正在尝试使用这样的 Http 拦截器进行注入:

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;
  }
}

如何实现 Observable 依赖。 KeycloakService.updateToken() returns 另一个 Observable,所以我需要等待响应然后添加授权 header。如果有任何提示,我将不胜感激。

使用switchMap等待super.get()返回的observable在发出响应之前解析

替换

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

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

Examples

我也要改:

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

有:

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

为了捕获 undefined 以及 null 选项