2017-07-06 57 views
0

我的應用使用angular2 http,現在我必須爲所有請求設置超時。對於單個請求,我正在執行此操作:如何在angular2上爲GET請求設置全局超時

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

如何爲我的應用程序擁有的所有獲取抽象出這個?

+0

見http://restlet.com/company/blog/2016/ 4月18日/相互作用-高效上帶有一個的RESTful服務與 - angular2和 - rxjs部分-3 /。 –

回答

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]}, 
] 
相關問題