python ruby-programming-language Smalltalk Vue.js Knockoutjs TypeScript JavaScript, OOPs JavaScript Angular 7, Interview Questions Angular 8,7,6,5,4 and 2 Interview Questions and Answers Angular 8,7,6,5,4 and 2 Interview Questions and Answers Angular 4 Angular 2 AngularJs 1.x NodeJs Perl Programming R Programming RequireJs Rust Programming Backbonejs closure programming language go-programming-language kotlin-programming-language
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

Hi there! Welcome to my blog. My name is Anil Singh. I'm a author of this blog. For more detail about me, kindly refer to this link..
My Blogs - http://code-sample.com and http://code-sample.xyz
My Books - Interview Questions and Answers Books- Get Your Book in 15+ Digital Stores Worldwide..

You Might Also Like
www.code-sample.com/. Powered by Blogger.
ASK Questions