如何在Angular2设置全局自定义页眉? [英] How do you set global custom headers in Angular2?

查看:556
本文介绍了如何在Angular2设置全局自定义页眉?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想设置页眉内容类型:应用程序/ JSON 在我所有的要求我的Angular2后端。我在主 app.js 文件中使用此。

 让标题=新的报头({
    内容类型,应用/ JSON
})
类MyOptions扩展BaseRequestOptions {
  标题:标题
}引导程序(App [
  提供(RequestOptions,{useClass:MyOptions})
  ROUTER_BINDINGS,
  HTTP_PROVIDERS,
  绑定(A​​PP_BASE_HREF).toValue('/')
])

我期待的 HTTP 来使用新的内容类型的所有用途,但这个code仍具有内容类型设置为文本/纯

  saveMaster(主){
  返回this.http
    。把(`$ {} config.API_URL /硕士/ $ {master._id}`,JSON.stringify(主))
    .MAP(RES => res.json())
}

我不得不手动设置为每个请求的报头得到它正常工作。难道我做错了什么?

注意:我要全局设置一个头选项,不必像在的这个解决方案


解决方案

  1. 更改 MyOptions 为:

类MyOptions扩展RequestOptions {
  构造函数(){
    超({
      方法:RequestMethod.Get,
      标题:新标题({
        内容类型:应用/ JSON,
        X-一些标头:一些内容
      });
    });
  }
}

<醇开始=2>

  • 提供(RequestOptions,{useClass:MyOptions}) HTTP_PROVIDERS (否则默认的 BaseRequestOptions 将被用来代替你的 MyOptions )。

  • 引导程序(App [
      // ...
      HTTP_PROVIDERS,
      提供(RequestOptions,{useClass:MyOptions})//&LT; - 后HTTP_PROVIDERS!
    ])

    请参阅这普拉克

    I want to set the header Content-type: application/json in all my requests to my backend in Angular2. I use this in my main app.js file.

    let headers = new Headers({
        'Content-Type', 'application/json'
    })
    class MyOptions extends BaseRequestOptions {
      headers: headers 
    }
    
    bootstrap(App, [
      provide(RequestOptions, {useClass: MyOptions}),
      ROUTER_BINDINGS,
      HTTP_PROVIDERS,
      bind(APP_BASE_HREF).toValue('/')
    ])
    

    I'm expecting all uses of Http to use the new content-type, but this code still has the content-type set to text/plain

    saveMaster (master) {
      return this.http
        .put(`${config.API_URL}/masters/${master._id}`, JSON.stringify(master))
        .map(res => res.json())
    }
    

    I have to manually set the headers for each request to get it work correctly. Am I doing something wrong?

    Note: I want to set a header option globally, not have to set it with every request type like is found in this solution.

    解决方案

    1. Change MyOptions to:

    class MyOptions extends RequestOptions {
      constructor() { 
        super({ 
          method: RequestMethod.Get,
          headers: new Headers({
            'Content-Type': 'application/json',
            'X-Some-Header': 'some-content'
          });
        });
      }
    }
    

    1. Put provide(RequestOptions, {useClass: MyOptions}) AFTER HTTP_PROVIDERS (otherwise default BaseRequestOptions will be used instead of your MyOptions).

    bootstrap(App, [
      // ...
      HTTP_PROVIDERS,
      provide(RequestOptions, {useClass: MyOptions}) // <- after HTTP_PROVIDERS!!!
    ])
    

    See this plunk

    这篇关于如何在Angular2设置全局自定义页眉?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆