8

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.

Shane Stillwell
  • 3,198
  • 5
  • 31
  • 53
  • 2
    Possible duplicate of [Angular2 - set headers for every request](http://stackoverflow.com/questions/34464108/angular2-set-headers-for-every-request) – Mark Rajcok Dec 29 '15 at 01:55
  • @MarkRajcok That answer is still setting custom headers for every type of request manually. I'll try alexpods solution tomorrow. – Shane Stillwell Dec 29 '15 at 04:59

1 Answers1

8
  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

alexpods
  • 47,475
  • 10
  • 100
  • 94
  • This work nicely. Sadly this does not work with dynamic headers (eg: header that depends on cookies that may change). The constructor will be only evaluated once at loading. – astreal Jun 29 '16 at 10:48
  • For dynamic headers, you can extend the http class and modify the `request` method to add custom headers for every request. I've written a comprehensive guide for this - http://www.adonespitogo.com/articles/angular-2-extending-http-provider/ – papar Nov 07 '16 at 03:12
  • For **NG4+** (I'm currently on Angular 6) this answer worked for me => https://stackoverflow.com/questions/34464108/angular-set-headers-for-every-request/45221680#45221680 – Eric D. Johnson Jan 07 '19 at 22:28