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