I realise the following code is not valid Angular, however I am just using it to try to visually illustrate what I'd like to achieve.
I'd like to extend the Angular HTTP client to add some headers.
I am imagining making a class that looks like this, where I extend the Angular http client, then in the constructor I set a default header:
import { Injectable } from '@angular/core'
import { HttpClient, HttpHandler } from '@angular/common/http'
import { AuthenticationService } from './authentication.service.ts'
@Injectable()
export class AuthenticatedHTTPClient extends HttpClient {
constructor(
handler: HttpHandler,
auth: AuthenticationService
){
super(handler)
this.headers.set('Authorization', this.auth.accessToken)
}
}
Now when I consume it with, for example:
constructor(
authHttp: AuthenticatedHTTPClient
){ }
...
this.authHttp.get('/api/something')
The authHttp client I am using will already have the header set.
Is this possible?
Angular has an interface, HttpInterceptor, that will allow you to achieve the functionality you are wanting in a much easier way.
You can read more about the HttpInterceptor interface here: https://angular.io/api/common/http/HttpInterceptor
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With