【发布时间】:2017-03-24 14:54:47
【问题描述】:
我需要 Angular 1.x 中的拦截器。 我在旧问题中找到了很多解决方案,但显然它们不再起作用了!
您能否提供适用于最新版本 Angular 2 的解决方案?
【问题讨论】:
-
看看:41998690
标签: angular angular2-http
我需要 Angular 1.x 中的拦截器。 我在旧问题中找到了很多解决方案,但显然它们不再起作用了!
您能否提供适用于最新版本 Angular 2 的解决方案?
【问题讨论】:
标签: angular angular2-http
您可以覆盖 Angular 的 Http 类,在其中添加标头,然后在您的模块中提供 CustomHttp 类:
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Rx';
import { RequestOptionsArgs, RequestOptions, ConnectionBackend, Http, Request, Response, Headers } from "@angular/http";
@Injectable()
export class CustomHttp extends Http {
headers: Headers = new Headers({ 'Something': 'Something' });
options1: RequestOptions = new RequestOptions({ headers: this.headers });
constructor(backend: ConnectionBackend,
defaultOptions: RequestOptions) {
super(backend, defaultOptions);
}
get(url: string, options?: RequestOptionsArgs) {
console.log('Custom get...');
return super.get(url, this.options1).catch(err => {
console.log(err);
});
}
}
您需要对post、put、delete 等执行相同的操作。
在你的模块中:
{ provide: Http,
useFactory: (
backend: XHRBackend,
defaultOptions: RequestOptions) =>
new CustomHttp(backend, defaultOptions),
deps: [XHRBackend, RequestOptions]
}
【讨论】: