Currently I used this static code in component .ts file but this one is not work. It returns unauthorized(401). But when I pass token as query string it works fine. Please give a working example for component .ts file.
import { HttpClient, HttpResponse ,HttpHeaders} from '@angular/common/http';
var t=`eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC9sb2NhbGhvc3Q6ODAwMFwvYXBpXC9sb2dpbiIsImlhdCI6MTUzNzcxNTMyNSwiZXhwIjoxNTM3NzE4OTI1LCJuYmYiOjE1Mzc3MTUzMjUsImp0aSI6IlBKWVhnSkVyblQ0WjdLTDAiLCJzdWIiOjYsInBydiI6Ijg3ZTBhZjFlZjlmZDE1ODEyZmRlYzk3MTUzYTE0ZTBiMDQ3NTQ2YWEifQ.1vz5lwPlg6orzkBJijsbBNZrnFnUedsGJUs7BUs0tmM`;
var headers_object = new HttpHeaders();
headers_object.append('Content-Type', 'application/json');
headers_object.append("Authorization", "Bearer " + t);
const httpOptions = {
headers: headers_object
};
this.http.post(
'http://localhost:8000/api/role/Post', {limit:10}, httpOptions
).subscribe(resp => {
this.roles = console.log(resp)
}
);
Add
AuthInterceptor
that will intercept all your http requests and add the token to its headers:Then register it in your
AppModule
:More about interceptors:
https://angular.io/guide/http#intercepting-requests-and-responses
interceptors are capable to add token in your Header
go through URL Bellow https://angular.io/guide/http#intercepting-requests-and-responses
Please create HttpHeaders object like this (instead of appending) ,
The problem with your code is that the
HttpHeaders
class is immutable, so when you callappend
it actually returns a new instance with the specified value, but does not modify the original object.Try this
Content-Type is set to json by default by
HttpClient
If you need to do send a the Authorization token in all your API calls, then it's better to use an interceptor as suggested by Martin