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';

@Injectable()
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

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 Blogs - https://code-sample.com and https://code-sample.xyz
My Book1 - BEST SELLING ANGULAR BOOK (INCLUDING ALL VERSIONS 2, 4, 5, 6, 7)
My Book2 - ANGULAR 2 INTERVIEW QUESTIONS BOOK - Both Books are Available on WorldWide.

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