Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
291 views
in Technique[技术] by (71.8m points)

content type - How do you set global custom headers in Angular2?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
  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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...