如何在angular2上为GET请求设置全局超时

时间:2017-07-06 01:54:45

标签: angular angular2-services

我的应用使用angular2 http,现在我必须为所有请求设置超时。对于单个请求,我执行此操作:

this.http.get(this.endPoint)
  .timeout(10000, new Error('timeout'))
  .map( res => res.json());

如何为我的应用程序获取的所有内容提取此内容?

1 个答案:

答案 0 :(得分:0)

我通过创建扩展Http类来解决这个问题。我不确定HttpService是否是最好的名字,但它对我有用。

import { Injectable } from '@angular/core';
import 'rxjs/add/operator/map';
import { Observable } from 'rxjs/Observable';
import {Http, XHRBackend, RequestOptions, Request, RequestOptionsArgs, Response} from '@angular/http';


@Injectable()
export class HttpService extends Http{
    constructor (backend: XHRBackend, options: RequestOptions) {
        super(backend, options);
    }

    request(url: string|Request, options?: RequestOptionsArgs): Observable<Response> {
        return super.request(url, options).timeout(5000, new Error('timeout'));
    }
}

我还必须将HttpService声明为提供者,并在app.module.ts上为其创建工厂

providers: [
  {provide: ErrorHandler, useClass: IonicErrorHandler},
  {provide: HttpService,useFactory: (backend: XHRBackend, options: RequestOptions) => {
      return new HttpService(backend, options);
      }, deps: [XHRBackend, RequestOptions] },
  {provide: AuthHttp, useFactory: getAuthHttp, deps: [HttpService]},
]