Check out our Angular Book Series.

How can I set headers in an Angular POST or PUT request?

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:


saveItem(item: ItemClas): Observable<Item> {
return this.http.put(`url`, item)
.pipe(
map(response =>
{
// process response
return response
})
);
}

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:


const headerObject = {};
headerObject['my-header-name'] = my-header-value;

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


return this.http.put(`url`, item, {headers: new HttpHeaders(headerObject),})

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

Comments (Comment Moderation is enabled. Your comment will not appear until approved.)
Comments are not allowed for this entry.
All Content Copyright 2005, 2006, 2007, 2008, 2009 Jeffry Houser. May not be reused without permission
BlogCFC was created by Raymond Camden. This blog is running version 5.9.2.002.