Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extend Angular's HTTP client?

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?

like image 402
David Alsh Avatar asked Apr 26 '26 00:04

David Alsh


1 Answers

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

like image 114
Michael Henderson Avatar answered Apr 27 '26 13:04

Michael Henderson