Angular2 拦截器工作不正常

Angular 2 interceptor is not working properly

我正在尝试创建一个自定义 http class 来扩展 Http 以像 AngularJS 拦截器一样工作 Angular 2. 我关注了其他 Whosebug 问题和一些教程但是我总是得到同样的错误,我找不到解决方案。

我有以下 Http 拦截器:

import { Injectable } from '@angular/core';
import { Http, ConnectionBackend, RequestOptions, RequestOptionsArgs, Response, Headers, Request } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/Rx';

@Injectable()
export class CustomHttp extends Http {
    constructor(backend: ConnectionBackend, defaultOptions: RequestOptions) {
        super(backend, defaultOptions);
    }

    request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> {
        options = new RequestOptions();
        let headers = new Headers();
        headers.append('X-Auth-Token', 'Bearer ' + localStorage.getItem('access-token'));
        options.headers = headers;
        return super.request(url, options);
    }
}

然后我将它添加到 app.module 中,如下所示:

  providers: [{
    provide: Http,
    useFactory: loadCustomHttp,
    deps: [XHRBackend, RequestOptions]
  }],

  export function loadCustomHttp(backend: XHRBackend, defaultOptions: RequestOptions) {
  return new CustomHttp(backend, defaultOptions);
}

我没有收到此配置的任何错误,但是当我发出任何请求时,我收到 401,因为未添加身份验证 header。示例请求可以是:

import { Http } from '@angular/http';

  getExample() {
    let url = this.urlBase + '/test';

    return this.http.get(url);
  }

任何帮助将不胜感激,提前致谢:)

url 可能是两种不同类型之一,字符串或请求,所以

request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> {
let token = localStorage.getItem('access-token');

if (token) {
  if (typeof url === 'string') {
    if (!options) {
      options = { headers: new Headers() };
    }
    options.headers.set('Authorization', `Bearer ${token}`);
    console.log('Url is string', options.headers.get('Authorization'));
  } else {
    url.headers.set('Authorization', `Bearer ${token}`);
    console.log('Url is Request', url.headers.get('Authorization'));
  }
}

return super.request(url, options);
}