2017-02-14 265 views
2

在角1,全局處理的HTTP響應狀態與$httpProvider完成:角2 HTTP響應攔截

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

@Injectable() 
export class HttpInterceptor extends Http { 

    constructor(xhrBackend: XHRBackend, requestOptions: RequestOptions) { 
    super(xhrBackend, requestOptions); 
    } 

    private catchErrors() { 
    return (response: Response) => { 
     if (response.status === 418) { 
      // do some stuff here 
     } 
     return Observable.throw(response); 
    }; 
    } 

    request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> { 
    return super.request(url, options) 
      .catch(this.catchErrors()); 
    } 
} 

angular.module('app', []) 
    .service('httpResponseInterceptor', ['$q', function ($q) { 
     this.response = function (response) { 
      if (response.status === 418) { 
       // do some stuff here 
      } 
      return response || $q.when(response); 
     }; 
     this.responseError = function (response) { 
      if (response.status === 418) { 
       // do some stuff here 
      } 
      return $q.reject(response); 
     }; 
    }]) 
    .config(['$httpProvider', function ($httpProvider) { 
     // do routing, etc. 

     $httpProvider.interceptors.push('httpResponseInterceptor'); 
    }]); 


在角2中,延伸等Http東西這個代替做

...並通過將其包括在app.module.ts中:

providers: [ 
    { provide: Http, useClass: HttpInterceptor } 
] 

參考見this stackoverflow answerthis gist


不過,我得到這個錯誤與上面的角2碼:

無法實例循環依賴! Http:in NgModule AppModule

回答

4

這個配置適用於我;我使用角2 V2.4.1:

app.module.ts

{ 
    provide: Http, 
    useFactory: (backend: XHRBackend, options: RequestOptions) => { 
     return new HttpInterceptor(backend, options); 
    }, 
    deps: [XHRBackend, RequestOptions] 
} 

HttpInterceptor.ts

import { Injectable } from '@angular/core'; 
import { 
    Http, 
    ConnectionBackend, 
    RequestOptions, 
    RequestOptionsArgs, 
    Request, 
    Response, 
    Headers 
} from '@angular/http'; 

import { Observable } from 'rxjs/Rx'; 

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

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

    ... 
} 
+0

感謝您對本! 'useFactory'和'deps'對我來說工作正常,而不是'useClass'。 –