将 header 附加到所有 Http 请求 -> Angular2
Append header to all Http Requests -> Angular2
我需要 Angular 1.x 中拦截器的等效项。
我在旧问题中找到了很多解决方案,但显然它们不再起作用了!
您能否提供适用于最新版本 Angular 2 的解决方案?
您可以覆盖 Angular 的 Http
class,在其中添加 headers,然后在您的模块中提供 CustomHttp
class:
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]
}
我需要 Angular 1.x 中拦截器的等效项。 我在旧问题中找到了很多解决方案,但显然它们不再起作用了!
您能否提供适用于最新版本 Angular 2 的解决方案?
您可以覆盖 Angular 的 Http
class,在其中添加 headers,然后在您的模块中提供 CustomHttp
class:
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]
}