首页 文章

全局添加标头和超时请求

提问于
浏览
2

我做了一个拦截器服务,看看请求的错误是401(unAuthorized)进入带有show的登录页面还是全局隐藏加载 . 但仍需要使用此服务(拦截器服务)全局添加标头,而不是在每个请求上添加标头 . 第二,我还需要添加超时(30000)如果请求没有回复这30秒的响应,我在每个请求它手动尝试它但我遇到了hideLoadding的问题,因为我也全局配置加载 . 拦截器服务代码:

export class HttpInterceptor extends Http {
  public loaderService: LoaderService

  constructor(backend: ConnectionBackend,
              defaultOptions: RequestOptions,
              public events: Events) {
    super(backend, defaultOptions);
  }

  get(url: string, options?: RequestOptionsArgs): Observable<Response> {
    return this.intercept(super.get(url, options));
  }

  post(url: string, body: string, options?: RequestOptionsArgs): Observable<Response> {
    return this.intercept(super.post(url, body, this.getRequestOptionArgs(options)));
  }


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

  intercept(observable: Observable<Response>): Observable<Response> {
    this.events.publish('showLoader');
    return observable
      .catch(
        (err) => {
          if (err.status == 401) {
            this.events.publish('unAuthorizedRequest', err);
            this.events.publish('hideLoader');
            return Observable.empty();
          } else {
            this.events.publish('hideLoader');
            return Observable.throw(err);

          }
        })
      .do(
        () => {
          this.events.publish('hideLoader');
          return Observable.empty();
        },
        () => {
          this.events.publish('hideLoader');
          return Observable.empty();
        }
      );
  }
}

在应用程序组件中:

this.events.subscribe('unAuthorizedRequest', (err) => {
      if (!_.endsWith(err.url, '/token')) {
        this.nav.setRoot(LoginPage);
      }
    });

    this.events.subscribe('showLoader', () => {
      this.numberOfLoading = this.numberOfLoading + 1;
      if(this.numberOfLoading === 1){
        this.loader = this.loaderService.presentLoading();
      }

    });

    this.events.subscribe('hideLoader', () => {
      if(this.numberOfLoading === 1){
        this.loader.dismiss();
        this.numberOfLoading = 0;
      }
      if(this.numberOfLoading > 0){
        this.numberOfLoading = this.numberOfLoading - 1;
      }

    });

1 回答

相关问题