How can you access the request headers in Angular? I am trying to get the Authorization Bearer access token to pass on to an api call through Angular.
CodePudding user response:
Use the interceptor to pass the Authorization Bearer access token to pass along with each API or Conditions you can add as well in the interceptor.
Command to generate the interceptor
ng generate interceptor [options] or ng g interceptor [options]
app.module.ts Configuration
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: LoaderInterceptor, multi: true }
]
https://angular.io/cli/generate#interceptor-command
Demo how Interceptor looks like
import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http';
import { Observable } from 'rxjs';
import { LocalStorageService } from '../../service/localStorage/local-storage.service';
import { api } from 'src/app/helpers/api';
import { encryptData } from 'src/app/helpers/helper';
@Injectable()
export class HeaderInterceptor implements HttpInterceptor {
constructor(private localStorageService: LocalStorageService) { }
intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
const authorization = this.localStorageService.getItem('access_token')
? this.localStorageService.getItem('access_token')
: '4763ae99-57d3-499f-b083-ec61ae6b510e';
return next.handle(
request.clone({
setHeaders: { Authorization: `Bearer ${authorization}` },
}),
);
}
}
CodePudding user response:
In the future, please provide what you have already tried and a more detailed description of what you are trying to do. I can give you a general answer, but if you were more specific and provided some code, I could give you a more specific answer.
Using the HttpClient
service:
To view the headers of a response add observe: 'response'
to the request options
parameter. The response will then be of type HttpResponse
with headers
as a property.
getSomething(url: string): Observable<HttpResponse<Object>> {
return this.http.get(url, { observe: 'response' });
}
To add headers to a request add headers
to the options
parameter of the request.
postSomething(
url: string,
data: any,
headerValue: string
): Observable<Object> {
return this.http.post(url, data, { headers: { 'my-header': headerValue } });
}
}