I need to set some Authorization headers after the user has logged in, for every subsequent request.
To set headers for a particular request,
You can create your own http client with some authorization header:
import {Injectable} from '@angular/core';
import {HttpClient, HttpHeaders} from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class HttpClientWithAuthorization {
constructor(private http: HttpClient) {}
createAuthorizationHeader(bearerToken: string): HttpHeaders {
const headerDict = {
Authorization: 'Bearer ' + bearerToken,
}
return new HttpHeaders(headerDict);
}
get(url, bearerToken) {
this.createAuthorizationHeader(bearerToken);
return this.http.get(url, {
headers: this.createAuthorizationHeader(bearerToken)
});
}
post(url, bearerToken, data) {
this.createAuthorizationHeader(bearerToken);
return this.http.post(url, data, {
headers: this.createAuthorizationHeader(bearerToken)
});
}
}
And then inject it instead of HttpClient
in your service class:
@Injectable({
providedIn: 'root'
})
export class SomeService {
constructor(readonly httpClientWithAuthorization: HttpClientWithAuthorization) {}
getSomething(): Observable