Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 232
Shane Stillwell Avatar asked Dec 28 '15 23:12

Shane Stillwell


People also ask

How do I get past HTTP headers?

In the Name field, enter the name of your header rule (for example, My header ). From the Type menu, select Request, and from the Action menu, select Set. In the Destination field, enter the name of the header affected by the selected action. In the Source field, enter where the content for the header comes from.

What are custom headers?

Custom headers allow site owners to upload their own “title” image to their site, which can be placed at the top of certain pages. These can be customized and cropped by the user through a visual editor in the Appearance > Header section of the admin panel. You may also place text beneath or on top of the header.

What is HTTP header in angular?

HTTP Headers let the client and the server share additional information about the HTTP request or response. For example, we use the content-type header to indicate the media type of the resource like JSON, text, blob, etc.


1 Answers

  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

like image 196
alexpods Avatar answered Oct 29 '22 15:10

alexpods