python ruby-programming-language Smalltalk Vue.js Knockoutjs TypeScript JavaScript, OOPs JavaScript 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
How To Set Authorization Headers in GET/POST Requests in Angular 4 or 5?

How To Set Authorization Headers in GET/POST Requests in Angular 4/5?

The Http Headers is immutable and each and every set () returns a new instance and applies the changes with lazy parsing.

HttpHeaders Constructor
constructor(headers?: string | { [name: string]: string | string[];});


Imports HttpHeaders from –
import {HttpHeaders } from '@angular/common/http';


ü  Stayed Informed -  HttpClientModule vs HttpClient

Example – for setting Headers and with multiple Headers
import { Component, OnInit } 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 implements OnInit {
  baseUrl ="https://code-sample.com/";
  users = null;

 // Inject HttpClient into your component or service.
  constructor(private http: HttpClient){  }

  //Load User info.
  ngOnInit(): void {
     // Make the HTTP request:
    this.http.get(this.baseUrl +'api/users/').subscribe(data => {
      this.users = data;
    },
    err => {
      console.log("Error- something is wrong!")
    });  
  }

  user ={
    id: 1,
    name: 'Anil Singh',
    user_Id:9979,
    site : 'https://code-sample.com'
  }

  ////Setting a header.
  addUser = function(){
    //Make the HTTP Post Request
    this.http.post(this.baseUrl +'api/addUser/', this.user, {
            headers: new HttpHeaders().set('Authorization', 'Auth_Token')
        })
        .subscribe(
          result => {
            console.log(result);
          },
          err => {
            console.log("Error- something is wrong!")
      });
  }

  //Setting multiple headers.
  addUserDetail = function(){
    //Make the HTTP Post Request
    this.http.post(this.baseUrl +'api/addUserDetail/', this.user, {
          headers: new HttpHeaders({
            'Authorization': 'Auth_Token',
            'RequestToken': 'a36cc2fa-dba4-4d00-a499-8bc129f16d12'
          })
        })
        .subscribe(
          result => {
            console.log(result);
          },
          err => {
            console.log("Error- something is wrong!")
      });
  }
}


Example 2 - Using HttpInterceptor
The Http Interceptor is an interface and used to implement the intercept method.

//Register an Interceptor (HTTP_INTERCEPTORS) in the app Module.
import {NgModule} from '@angular/core';
import {HTTP_INTERCEPTORS} from '@angular/common/http';

@NgModule({
  providers: [{
    provide: HTTP_INTERCEPTORS,
    useClass: MyInterceptor,
    multi: true,
  }],
})
export class AppModule {}


And
//The HttpInterceptor is an interface and used to implement the intercept method.
import {Injectable} from '@angular/core';
import {HttpEvent, HttpInterceptor, HttpHandler, HttpRequest} from '@angular/common/http';

@Injectable()
export class MyInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const reqHeader = req.clone({headers: req.headers.set('Authorization', 'MyAuthToken')});
    return next.handle(reqHeader);
  }
}



I hope you are enjoying with this post! Please share with you friends!! Thank you!!!
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