7 HttpHeaders

How to set a custom header on the request?

How to set a custom header on the request?
To set a custom header on the request, firstly we need to instantiate HttpHeaders() object and pass ('header',  'value') into a function.
let headers = new HttpHeaders().set('Content-Type', 'text');

In the above example we set “Content-Type” header value to be “text” and the default header “Content-Type” is – “application/json”

It is of type immutable Map so if you assign a new value it will reinitialize the object.
let requestHeaders = new HttpHeaders().set('Content-Type', 'application/json');
requestHeaders = requestHeaders.set('authorization', 'Bearer ' + token);

We can also append headers by chaining HttpHeaders() constructor and will look like this-
let requestheaders = new HttpHeaders().set('Content-Type', 'application/json')
                    .set('authorization', 'Bearer ' + token);

And final request with custom headers will look like this –
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';

export class CustomerService {
  //Inject HttpClient into your components or services
  constructor(private http: HttpClient) { }

  //Set Headers
  requestHeaders = new HttpHeaders().set('Content-Type', 'text')
              .append('Authorization', 'CustomToke_AFA96A3429A9524');
  //Get Customer list
  getCustomers() {
    this.http.get('https://code-sample.com/customerjson', {
        headers: this.requestHeaders
    }).map((data:HttpEvent<object>) => { console.log(data) })

For more detail kindly refer the link.... 

Anil Singh is an author, tech blogger, and software programmer. Book writing, tech blogging is something do extra and Anil love doing it. For more detail, kindly refer to this link..

My Tech Blog - https://www.code-sample.com/
My Books - Book 1 and Book 2

www.code-sample.com/. Powered by Blogger.