In my previous article I spoke about accessing HTTP header values in an Angular GET request. Now, I'm going to show you how to set them as part of an HTTP PUT or POST request.

A simple update, might go something like this:

view plain print about
1saveItem(item: ItemClas): Observable<Item> {
2 return this.http.put(`url`, item)
3 .pipe(
4 map(response =>
{
5 // process response
6 return response
7 })
8 );
9}

We call a simple http.put() give it the URL and the item w are updating is the body. We process, and return the results. All good; this works great.

But, what happens when we want to send a custom header to the request? There is third parameter to a put() or post() call . It is a configuration object, and we can include our headers in there.

First, create the header:

view plain print about
1const headerObject = {};
2 headerObject['my-header-name'] = my-header-value;

Then create the configuration object, with a headers property, that has the value of HttpHeaders object.

view plain print about
1return this.http.put(`url`, item, {headers: new HttpHeaders(headerObject),})

That's all you need to properly add the header to the service call.