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 answer和this gist。
不過,我得到這個錯誤與上面的角2碼:
無法實例循環依賴! Http:in NgModule AppModule
感謝您對本! 'useFactory'和'deps'對我來說工作正常,而不是'useClass'。 –