Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Set Metadata in HTTP Headers with Angular HttpHeaders

    4 - 6

    Besides sending (or requesting) the actual data to the server API, there’s also often the need to send further metadata that helps the server to correctly interpret our request. Such data is most often sent using HTTP headers. In this lesson we learn how to leverage Angular’s HttpClient to set such headers. Note that when you have to continuously send certain application headers to the backend, for each single HTTP call that is being made, you may be better served by placing them in an HTTP interceptor. Take a look at this lesson for more details on how to implement that.



    Become a Member to view code

    You must be a Pro Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    orLog In




    Here we have a simple component which uses a people service, which internally used that fetchPeople function to issue an HTTP get call to this endpoint here. When I click here, we get the data from that endpoint. It gets visualized here on the UI.

    Now in many cases, we also need to send some HTTP header. For instance, if we inspect here the call that gets made, we can see that there is a header section. Basically here, we have the general effect where the URL is displayed. Then we have the response headers which come back from the server.

    We are especially interested here in the request headers, which get sent to the server. One simple example could be to submit, for instance, the current language of the user. With the new HTTP client, which here it resides in the Angular common HTTP package, this is quite easy.

    We can simply here pass a second parameter. Now we need to import here the HTTP header type, and then on the object here, we can specify the headers property, instantiate here a new HTTP headers object, and set the header which we want.

    For instance, let's call this app language. As a value, I pass simply a string, which is in this case is IT for Italian. If I now click that button and inspect again our header section, I can scroll down. Here we see our custom header which gets submitted to the server.

    Now if this header is something you want to send for each request that is being executed against the server, you might think of moving this part here into an interceptor, an HTTP interceptor, but this is a different topic for a different lesson.