【问题标题】:Append header to all Http Requests -> Angular2将标头附加到所有 Http 请求 -> Angular2
【发布时间】:2017-03-24 14:54:47
【问题描述】:

我需要 Angular 1.x 中的拦截器。 我在旧问题中找到了很多解决方案,但显然它们不再起作用了!

您能否提供适用于最新版本 Angular 2 的解决方案?

【问题讨论】:

标签: angular angular2-http


【解决方案1】:

您可以覆盖 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);
    });
}
}

您需要对postputdelete 等执行相同的操作。 在你的模块中:

{ provide: Http, 
    useFactory: (
        backend: XHRBackend,
        defaultOptions: RequestOptions) =>
        new CustomHttp(backend, defaultOptions),
    deps: [XHRBackend, RequestOptions]
}

【讨论】:

  • 好吧,谢谢伙计!我只需要最后一部分(如何在 NgModule 中声明新服务),它立即生效!
  • @Nano 很高兴我能提供帮助,如果对您有帮助,请考虑将我的回答标记为已接受。 :)
猜你喜欢
  • 1970-01-01
  • 2017-10-12
  • 1970-01-01
  • 2017-03-07
  • 1970-01-01
  • 1970-01-01
  • 2017-02-15
  • 2012-12-01
  • 2023-03-12
相关资源
最近更新 更多