如何在Angular 2中配置_defaultOptions.headers(扩展Http类)

时间:2016-07-14 10:34:35

标签: angular xmlhttprequest content-type

我尝试为HXR请求设置HEADERS,以便" Content-Type" :" application / x-www-form-urlencoded; charset = utf-8" 对于任何ajax调用我都会这样做,但是我在尝试扩展Http类时遇到了几个错误

import {Http, RequestOptions, ConnectionBackend} from "@angular/http";

export class HttpCustom extends Http{

    constructor(_backend: ConnectionBackend, _defaultOptions: RequestOptions){
        super(_backend, _defaultOptions);
        this._defaultOptions.headers.set("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
    }

}

有没有人知道如何正确扩展Http甚至是一个不同的解决方案来设置HEADERS一次?

1 个答案:

答案 0 :(得分:0)

您可以从RequestOptions类扩展merge方法

export class AppRequestOptions extends RequestOptions {

  merge(options?:RequestOptionsArgs):RequestOptions {

    let headers = options.headers || new Headers;
    headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
    options.headers = headers;

    return super.merge(options);
  }
}

然后在app bootstrap中提供自定义类

bootstrap(AppComponent, [
          HTTP_PROVIDERS,
          {provide: RequestOptions, useClass: AppRequestOptions })
]);

应该就够了。