angular - 将 header 附加到所有 Http 请求 -> Angular2

标签 angular angular2-http

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

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

最佳答案

您可以重写 Angular 的 Http 类,在其中添加 header ,然后在模块中提供 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]
}

关于angular - 将 header 附加到所有 Http 请求 -> Angular2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43002683/

相关文章:

angular - 如何在 Angular 5 (ngx-translate) 中对翻译列表进行排序

javascript - Angular:其中生命周期钩子(Hook)是组件可用的输入数据

Angular ngrx@effect 基本问题 : Type 'Observable<void>' is not assignable to type

animation - Angular2 Animations::Easings 没有按预期工作

angular - 是否有可能以某种方式同步调用异步 ionic 存储?

angular - 如何为 AngularJS 2 编写 http 拦截器?

angular - 使用 angular2 发送身份验证凭据

typescript - Angular 2 使用可迭代数组链接 Http Get 请求

javascript - 滚动时 Angular 5 粘性菜单

angular - 可观察 map 功能未运行(Angular2,http)