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

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.
^