Angular - How to Set Headers in Httpclient Request?

By Hardik Savani May 2, 2024 Category : Angular

This post is focused on how to set headers in httpclient angular. let’s discuss about how to set header in httpclient in angular. We will use angular httpclient with headers. This article will give you simple example of angular httpclient post response headers. follow bellow step for how to set headers in angular http post.

In this example, i will show you how to set headers in http request. we will use HttpHeaders to pass custom headers in angular http get, post, put and delete request. you can use this example in angular 8, angular 9, angular 10, angular 11, angular 12, angular 13, angular 14, angular 15, angular 16 and angular 17 versions.

Solution:

const headers = new HttpHeaders({'Content-Type':'application/json; charset=utf-8'});

const requestOptions = { headers: headers };

this.http

.get('http://localhost:8001/events.php', requestOptions)

.subscribe((res: any) => {

console.log(res);

});

Let's see below component ts file code:

src/app/app.component.ts

import { Component } from '@angular/core';

import { HttpClient, HttpHeaders } from '@angular/common/http';

@Component({

selector: 'app-root',

templateUrl: './app.component.html',

styleUrls: ['./app.component.css']

})

export class AppComponent {

title = 'fullcal';

/*------------------------------------------

--------------------------------------------

Define constructor

--------------------------------------------

--------------------------------------------*/

constructor(private http: HttpClient) {}

/*------------------------------------------

--------------------------------------------

Define ngOnInit()

--------------------------------------------

--------------------------------------------*/

ngOnInit() {

const headers = new HttpHeaders({

'Content-Type':'application/json; charset=utf-8',

'myCustomHeader':'itsolutionstuff.com'

});

const requestOptions = { headers: headers };

this.http

.get('http://localhost:8001/events.php', requestOptions)

.subscribe((res: any) => {

console.log(res);

});

}

}

Output:

I hope it can help you...

Tags :
Shares