Angular - How to Set Headers in Httpclient Request?
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...
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- Angular 13 Routing Module Example Tutorial
- Angular 13 HttpClient & Http Services Tutorial Example
- Angular 13 CRUD Application Example Tutorial
- Angular 11 Http Client Service Example
- Angular HttpClient with Observable Example
- Angular HttpClient Delete Example | Angular Http Delete Request Example
- Angular HttpClient Get Example | Angular Http Get Request Example
- Angular Service with Httpclient Example
- Angular Http Post Request Example
- Angular 9/8 HttpClient for Sending Http Request Example