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

watcher using RxJS

After recently diving into the Observable and Observer pattern, I came across various resources that describe Observable as a producer and Observer as a consumer. However, as I analyzed the code snippet below, I found myself puzzled by the role of the obse ...

Error message 'Chart was not disposed' is displayed in amChart while rendering live data through a socket connection

I encountered a similar issue with the amChart displaying a "chart was not disposed" warning, leading to memory leakage. To find a solution, I referred to the following guide: However, since I am updating the chart in real-time using socket connections a ...

What is the method for utilizing a class variable without assigning a value to it initially

class testClass { student: { name: string, age: number } constructor(options?: any) { this.student = { name: '', age: 0 }; } setStudent(name:string, age:number) { this.student.name ...

Tips for incorporating runtime configuration into an Angular module and effectively leveraging it

After setting up Apollo Angular, I encountered a challenge in src/app/graphql.module.ts src/app/graphql.module.ts import { NgModule } from '@angular/core'; import { APOLLO_OPTIONS } from 'apollo-angular'; import { ApolloClientOptions, I ...

What steps can be taken to ensure that all object properties become reactive?

Let's dive into this simplified scenario: interface Pup { name: string; age: number; } const puppy: Pup = { name: 'Rex', age: 3, }; The goal here is to establish a reactive link for each attribute within the puppy object. The usua ...

Creating a model and assigning values in TypeScript

I am currently developing an angular application and need to send data to a post API. The JSON structure I am working with is as follows: { "name": "julie", "id": 1, "PersonalDetails": { "hom ...

Azure deployment of a proprietary npm package

As a developer with git integration for my Angular web site, I have successfully checked code into Git and deployed it to Azure. Everything was running smoothly until I encountered an issue when trying to pull a private npm package. It dawned on me that I ...

Is there a way for me to program the back button to navigate to the previous step?

I am currently developing a quiz application using a JSON file. How can I implement functionality for the back button to return to the previous step or selection made by the user? const navigateBack = () => { let index = 1; axios.get('http ...

Stop allowing the entry of zero after a minus sign

One of the features on our platform allows users to input a number that will be automatically converted to have a negative sign. However, we want to ensure that users are unable to manually add a negative sign themselves. We need to find a solution to pre ...

What kind of type is recommended to use when working with async dispatch in coding?

For my TypeScript and React project, I am currently working on an action file called loginAction.tsx. In this file, there is a specific line of code that handles the login functionality: export const login = (obj) => async dispatch => { dispatch( ...

Is it possible that Typescript does not use type-guard to check for undefined when verifying the truthiness of a variable?

class Base {} function log(arg: number) { console.log(arg); } function fn<T extends typeof Base>( instance: Partial<InstanceType<T>>, key: keyof InstanceType<T>, ) { const val = instance[key]; if (val) { ...

I am interested in creating an input range slider using React and TypeScript

This code was used to create a slider functionality import { mainModule } from 'process'; import React, { useState } from 'react'; import styled from 'styled-components'; const DragScaleBar = () => { const [value, setV ...

Tips for generating a fixed-length array from multiple arrays with different lengths, focusing on selecting items from each array according to their significance

In order to create a quiz, I am looking to extract 'questions' from various 'topic' arrays. These topics are selected based on the user's preference and are used to populate a question bank for a 20-question quiz. The topics rated ...

I'm fascinated by the way well-known websites like The Guardian are utilizing Angular, as I often notice that when I click on links, the entire page reloads

As a beginner in Angular, I recently explored popular websites that implement Angular or React. I discovered sites like The Guardian, New York Times, and Netflix. However, most of these sites have links that open in new pages, while the remaining ones ut ...

Is it possible to initiate the onchange event in Angular programmatically using Typescript?

Despite changing the value of an input tag after returning a value from a dialog box (MatDialogRef), the associated change event fails to trigger. Attempts to use dispatchEvent have been made, but creating the event for triggering is not desired as per fo ...

Angular CLI - Monitoring libraries for updates to trigger rebuilding of dependent applications

Currently, I am in the process of creating an Angular Library with the usual setup where I have my main library project and another project where I utilize the output of the built library. My goal is to set up a system that automatically monitors changes ...

What are the best scenarios for implementing modules, components, or standalone components in Angular 17?

Apologies if this question has been posed before, but I'm still navigating my way through Angular and could use some guidance on when to utilize modules, components, or stand-alone components. For instance, if I am constructing a modest website consi ...

During rendering, the instance attempts to reference the "handleSelect" property or method which is not defined

I've incorporated the Element-UI NavMenu component into my web application to create a navigation bar using Vue.JS with TypeScript. In order to achieve this, I have created a Vue component within a directory called "navBar," which contains the follow ...

angular-ouath2-oidc fails to redirect following user authorization

I'm working on implementing angular-oauth2-oicd for obtaining users' permission to access their basecamp3 accounts. The application is able to successfully load the access request, but I'm facing an issue where upon clicking 'grant acce ...

How to filter an array in Angular 4 without the need for creating a new array and then displaying the filtered results within the same

In my collection of students, I have their names paired with their academic outcomes. studentResults = [ {name: 'Adam', result : 'Passed'}, {name: 'Alan', result : 'Failed'}, {name : 'Sandy', result : &ap ...