The art of expanding Angular's HTTP client functionality

I understand that the following code is not valid in Angular, but I am using it for visual demonstration purposes.

My goal is to enhance the Angular HTTP client by adding custom headers.

I envision creating a class like this, where I extend the Angular http client and set a default header in the constructor:

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)
    }
}

When consuming it with something like:

constructor(
    authHttp: AuthenticatedHTTPClient
){ }

...

this.authHttp.get('/api/something')

The authHttp client being used will already have the header set. Is this feasible?

Answer №1

If you're looking for a simpler way to achieve the functionality you desire in Angular, consider using the HttpInterceptor interface. It provides an easier solution to your problem.

To learn more about the capabilities of the HttpInterceptor interface, check out this link: https://angular.io/api/common/http/HttpInterceptor

Answer №2

Setting a Customized Header for each Method might be the solution you are looking for...

Give it a try!

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';

@Injectable()
export class AppServices {

  public httpHeaders:any;
  public httpGlobalOptions:any;
  public CustomHttpHeader:any;

  constructor(private http:HttpClient) {
    this.httpGlobalOptions = {
      headers: new HttpHeaders({
        'Content-Type':  'application/json',
      })
      };

  }

  methodCustomHeaders(){
    /* Set the Custom Header here */
    this.CustomHttpHeader = { 
        headers: new HttpHeaders(
                        { 'Authorization':  'Bearer ABCDEF', 'Content-Type':'application/json' }
                    ) 
    };

    return this.http.get("/your-path-service/", this.CustomHttpHeader);
  }

  methodGlobalHeader(){
    /* Use the Global Header here */
     return this.http.get("/your-path-service/", this.httpGlobalOptions);
  }

}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to retrieve a data type from an array using typescript?

Can Typescript automatically declare a type that retrieves the inner type of an array? For instance: Assume the following code snippet already exists: export interface Cache { events: Event[], users: User[] } type CacheType = Event[] | User[]; ...

Alter the entity type when passing it as a parameter

Trying to alter the Entity type, I am invoking a function that requires two parameters - one being the entity and the other a location. However, when trying to assign a Type for the first entity, it throws an error: Error: Argument of type 'Node<En ...

What is the process for creating a unit test case for an Angular service page?

How can I create test cases for the service page using Jasmine? I attempted to write unit tests for the following function. service.page.ts get(): Observable<Array<modelsample>> { const endpoint = "URL" ; return ...

Angular script error when running 'npm run' on select computers causing Unix command issues for some users but not all

Recently, I've encountered a puzzling issue at my workplace that has been difficult to diagnose. We utilize scripts in npm within the Angular framework to launch a local server instance. Strangely enough, some of my colleagues' computers are thro ...

The gap between columns in Bootstrap grids

Currently, I am dynamically fetching "boxes" and adding them to the HTML document using ngFor. The number of boxes is unknown in advance. Here is the code I am currently using: <div *ngIf="items && items.length" class="row"&g ...

Issue encountered on IIS 7.x server during deployment with HTTPS

Currently, I am running an Angular + .Net 4.5 fullStack application on IIS V7.5 with Windows Server. To conduct additional tests, I am using multiple instances of the same site with different versions of the application deployed on the same host. Each inst ...

Unable to locate module '@angular/core' while utilizing PrimeNG

After installing PrimeNg, I attempted to use the sidebar component in my project. However, upon running the project, an error occurred: ERROR in /home/haddad/projects/node_modules/primeng/components/sidebar/sidebar.d.ts (1,97): Cannot find module '@a ...

Difficulty encountered while trying to run the ngx-admin dashboard designed for Angular

I encountered some issues during the installation of node modules. Can someone please assist me with this? Angular CLI: 13.3.0 Node: 16.14.2 Click here to view the list of problems Any help would be greatly appreciated. ...

Checking for full template type compatibility in Angular 9 reveals cases of incompatible types

I have an Angular (+ Angular Material) 9.1.0 application up and running. Recently, I decided to enhance the type checking in my project's tsconfig.json by adding the following configuration: "angularCompilerOptions": { "strictTemplates": true, ...

Encountering difficulties while attempting to transition from angular 9 to angular 10

I attempted to upgrade my Angular project by running the following commands: $ ng update @angular/core@9 @angular/cli@9 $ ng update @angular/core @angular/cli However, when I executed the last command in the console, it resulted in an error message: Your ...

Using a loop variable within a callback function in JavaScript/TypeScript: Tips and tricks

I have a method in my TypeScript file that looks like this: getInitialBatches() { var i = 0; for (var dto of this.transferDTO.stockMovesDTOs) { i++; this.queryResourceService .getBatchIdUsingGET(this.batchParams) ...

Leveraging the power of LocalStorage in Ionic 2

Trying to collect data from two text fields and store it using LocalStorage has proven tricky. Below is the code I have set up, but unfortunately it's not functioning as expected. Can you provide guidance on how to resolve this issue? In page1.html ...

Can you provide details on the capabilities of Appium for webviews on Android devices?

I attempted to utilize the following capabilities { maxInstances: 1, browserName: '', appiumVersion: '1.18.2', platformName: 'android', platformVersion: '10.0', deviceName: 'd ...

What causes the Angular router URL to vary from the document location on reload while employing CanActivate?

My Angular 2 router setup seems to be causing some issues. When I refresh the page, I've noticed that the router object's URL value is different from the location.hash property of the document. For example, when I check router.url, I get "/", bu ...

How to determine the presence of 'document' in Typecsript and NextJS

Incorporating NextJS means some server-side code rendering, which I can manage. However, I'm facing a challenge when trying to check for set cookies. I attempted: !!document && !!document.cookie as well as document !== undefined && ...

How to implement div scrolling on button click using Angular 4

Is there a way to make the contents of a div scroll to the left when one button is clicked and to the right when another button is clicked? I've tried using ScrollLeft, but it doesn't seem to be working... Here's the HTML code: <button ...

What is the best way to send an array of locationIds to the getLocationData service?

Seeking Assistance on Sending an Array of Location IDs to a Service I currently have an array consisting of location IDs. locationArr=[40871, 60009, 38149, 40868, 43240, 15299, 53897, 40976, 38151, 23183, 38152, 78579, 23180, 40977, 23176, 39565, 40884, ...

What is the best way to integrate ng-bootstrap into an nx mono repository?

Encountering an issue when attempting to install ng-bootstrap in a multi-project mono repo using Nx. The error message received is as follows: npx ng add @ng-bootstrap/ng-bootstrap --project=web-app The add command needs to be executed in an Angular proje ...

Error in Angular: Trying to access the property 'id' of an undefined value

I am facing an issue with a div tag in my HTML file. The code snippet looks like this: <div *ngIf="chat.asReceiver.id != user?.id; else otherParty"> Unfortunately, it always returns the following error: ERROR TypeError: Cannot read propert ...

A Guide to Filtering MongoDB Data Using Array Values

I am trying to extract specific data from a document in my collection that contains values stored in an array. { "name": "ABC", "details": [ {"color": "red", "price": 20000}, {" ...