重新发送请求角度 2 [英] Resend request angular 2

查看:44
本文介绍了重新发送请求角度 2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In angular 2 app every request to API has header with token, in case token has expired API responds with 401 http code. I have a method to update token, but how I can resend previous request pausing others while a new token is in the process of getting?

推荐答案

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

You could extend the Http class for this this way, catch the error using the catch operator of observables:

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

An approach could be to extend the HTTP object to intercept errors:

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

并按如下所述进行注册:

and register it as described below:

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

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

Within the callback defined in the catch operator, you could call your method to update the token, get the result, set the new token on the source request and execute it again. This would be completely transparent.

这是一个示例:

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

编辑

要暂停"其他请求,您需要使用 doshare 运算符在 getToken 方法中实现一些缓存:

To "pause" other requests you need to implement some caching within the getToken method using the do and share operators:

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

这篇关于重新发送请求角度 2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆