重新发送请求角度2

时间:2016-05-18 17:39:45

标签: angular rxjs5 angular2-http

在angular 2应用程序中,对API的每个请求都有带令牌的标头,以防令牌已过期API响应401 http代码。我有一个更新令牌的方法,但是当新令牌正在获取时,我如何重新发送暂停其他请求的先前请求?

1 个答案:

答案 0 :(得分:2)

您可以通过这种方式扩展Http类,使用observables的catch运算符捕获错误:

一种方法可能是扩展HTTP对象以拦截错误:

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

  request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> {
    console.log('request...');
    return super.request(url, options).catch(res => {
      // do something
    });        
  }

  get(url: string, options?: RequestOptionsArgs): Observable<Response> {
    console.log('get...');
    return super.get(url, options).catch(res => {
      // do something
    });
  }
}

并按如下所述进行注册:

bootstrap(AppComponent, [HTTP_PROVIDERS,
    new Provider(Http, {
      useFactory: (backend: XHRBackend, defaultOptions: RequestOptions) => new CustomHttp(backend, defaultOptions),
      deps: [XHRBackend, RequestOptions]
  })
]);

catch运算符中定义的回调中,您可以调用方法来更新令牌,获取结果,在源请求上设置新令牌并再次执行。这将是完全透明的。

以下是一个示例:

get(url: string, options?: RequestOptionsArgs): Observable<Response> {
    return super.get(url, options).catch(res => {
      if (res.status === 401) {
        return this.getToken().flatMap(token => {
          var sourceOptions = options || {};
          var headers = sourceOptions.headers || new Headers();
          headers.append('Authorization', token); // for example
          return super.get(url, options);
        });
      }

      return Observable.throw(res);
    });
  }

修改

暂停&#34;暂停&#34;使用getTokendo运算符在share方法中实现某些缓存所需的其他请求:

getToken() {
  if (hasTokenExpired()) {
    this.token = null;
    this.tokenObservable = null;
  }

  if (this.token) {
    // Gotten the new token
    return Observable.of(this.token);
  } else if (this.tokenObservable) {
    // Request in progress...
    return this.tokenObservable;
  } else {
    // Execute the "refresh token" request
    return this.get('/refreshToken')
      .map(res => res.json)
      .do(token => {
        this.token = token;
        this.tokenObservable = null;
      })
      .share();
  }
}