Having trouble setting specific custom headers with HttpHeaders in Angular 8

I have been attempting to make a GET request to SAP Business Objects that requires custom headers. I followed the Angular documentation on how to define these headers using the HttpHeaders class. However, it seems like the custom headers (X-...) are not being recognized.

Below is the code snippet where I create the headers and execute the GET request:

getEnvId(token: string) {

    this.tokenHdr = { 
      headers: new HttpHeaders({
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        'Accept-Language': 'en-US',
        'X-SAP-PVL': 'en-US',
        'X-SAP-LogonToken': token
      })
    }

    console.log(this.tokenHdr);

    return this._http.get('http://' + this.environment + '/biprws/infostore/cuid_' + this.reportCuid, this.tokenHdr)
  }

When logging the this.tokenHdr object, it displays as shown in the following image: https://i.sstatic.net/AECIx.png

The error response I receive is depicted here: https://i.sstatic.net/v9evM.png

Prior to this step, I am able to successfully retrieve the token and print it to the console. The token is obtained through a POST request without any custom headers, leading me to suspect that the issue lies with the custom headers.

Observing the Network tab in the browser's developer tools reveals additional insights: https://i.sstatic.net/48837.png

Answer №2

Consider implementing the following solution to address your issue: By using the set method, you can return the headers object each time. This approach ensures that the original headers from the intercepted request are preserved.

let headers = new HttpHeaders().set('Accept', 'application/json')
     .set('Content-Type' , 'application/json')
     .set('Accept-Language','en-US')
     .set('X-SAP-PVL', 'en-US')
     .set('X-SAP-LogonToken', token)

let apiUrl: string = 'http://url';

return this.http.get(apiUrl, {headers});

Take a look at the modifications I made below:

//to retrieve the token

  loadToken() {
    const token = localStorage.getItem('token');
    this.authToken = token;
  }

 createAuthHeader() {
    this.loadToken();
    const headers = new HttpHeaders().set(
      'Authorization',
      `Bearer ${this.authToken}`
    );
    return { headers };
  }

  someTest() {
    return this.http.get(`${this.url}/count`, 
      this.createAuthHeader());
  }

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

Angular 14 presents an issue where the injectable 'PlatformLocation' requires compilation with the JIT compiler; however, the '@angular/compiler' module is currently missing

I've encountered the following error and have tried multiple solutions, but none of them have been successful: Error: The injectable 'PlatformLocation' requires JIT compilation with '@angular/compiler', which is not available. ...

Type Vue does not contain the specified property

I am encountering an issue where I am using ref to retrieve a value, but I keep receiving the error message "Property 'value' does not exist on type 'Vue'". Below is the code snippet causing the problem: confirmPasswordRules: [ ...

Make sure to load Meteor.user() prior to initializing Angular 2

I am encountering an issue while setting up a new Meteor - Angular2 application where I am struggling to verify the logged-in user within my router. Below is my current auth-guard.service.ts content featuring an AdminAuthGuard that utilizes implements Can ...

"An auto-invoking function is declared in a TypeScript compiled module with a var statement

Currently, I am in the process of converting an existing AngularJS (1.x) project to TypeScript. The code seems to be functioning properly, but there are some aspects that leave me with questions. In JavaScript, I declare a module like this: (function() { ...

Exploring Angular 6: Step-by-step guide to nesting objects within objects

I have a problem with posting data to my API built with Spring Boot. workflow : any = { name : "CMD1", items : [ { name : "work1", content : null }, { name : "work2", content : null } ] } In Angular, I created a ...

Exploring the Relationship Between the ngOnInit and ionViewWillLoad Lifecycle Hooks

After a few months of utilizing Ionic Framework (ionic-angular 3.9.2 latest) for developing Progressive Web Apps, I find myself pondering the distinction between ngOnInit and ionViewWillLoad. If my understanding serves me right, ngOnInit is an Angular lif ...

steps to authenticate with dynamic database information instead of hard-coded data

After following a tutorial, I successfully created my first register login system in dot net and angular. The issue I encountered is that the author used static data in the tutorial's code example. However, I want to implement my own database data. As ...

Challenges with dependencies during the transition to Angular 8

After migrating my application to Angular 8, I encountered a dependency issue in my package.json file when running the application. Upon updating angular/cli, an error message is displayed when trying to launch the application: An unhandled exception o ...

Delay in Angular 2 Change Detection when using Arrays and @Inputs is experienced for a few seconds

Trying to wrap my head around change detection in Angular 2 has been a bit challenging with the plethora of information available. I've been working with "buckets" fetched from Firebase, pushing them into an array, and passing that array into a child ...

react-spring - tips for effectively addressing TypeScript typechecking challenges

Using react-spring with typescript has presented some challenges, even on the initial test, as evident from the prominent typescript checking issues below. Could there be a fundamental error in the way I am utilizing it, or is there a relatively painless ...

Error message: "The toJSON method is not found for the item in the nested array of

Encountering an issue with NSwag in my Angular project where it throws an error when attempting to send data if the object contains a nested array of objects like this: export interface IJobAdDto { mainJobAd: JobAddDetailsDto; differentLanguageJobA ...

Exploring Child Records with Angular4 and RxJS Observables

I am currently in the process of developing a frontend for a blog. My main objective is to retrieve an array of posts from the API, then make additional API calls for each post to fetch the featured image objects and attach them to their respective parent ...

Capture the keyboard event for the delete button in Angular 2

I am dealing with multiple records displayed in a gridview and need to select and delete them simultaneously. Once the records are selected, I aim to remove them in one go. Does anyone have a solution on how to trigger the delete event in angular2 when t ...

Navigating to a property List to then view a property Detail page and showcase the specific details of the selected property, encountering a 404

Using the httpClient to fetch data from a local json file, everything operates smoothly in the propertylist. However, when selecting a property and wanting to show its details on a new page, I'm struggling to grasp the concept despite watching numerou ...

Ways to utilize the useRef method within the useContext hook while implementing Typescript

Struggling to incorporate useRef into my global Next.js useContext function while utilizing TypeScript. Attempted approach and encountered errors: interface tripAttributes{ tripTitle: string } const initialTripState: tripAttributes = { tripTitle ...

Error in Angular: Unable to load resource - server returned a 404 status code on IIS

My Angular-13 application is hosted on IIS under the name: employee-app The URL for accessing it is: https://localhost:8443/employee-app/ To set it up, I ran the command: ng build --base-href "/employee-app" I also included a Web.config fi ...

Managing the initial form load in Angular: tips and tricks

I am struggling with a form that includes "from" and "to" dates, a select component for products, and another select for product varieties. My issue is that I cannot load the default value on initial load. When selecting a product, the corresponding varie ...

Spin rectangular image within boundary using angular 6

I am trying to achieve a rotating effect on a rectangular image within a frame of the same dimensions, as shown below: <div style="border:1px solid #d3d3d3;width:208px;height:250px"> <img style="width:208px;height:250px" src="https://www.webslak ...

Structure of document

Could anyone clarify for me the meaning of (callback[, thisObject]); that is mentioned in the TypeScript documentation here? I am particularly curious about the brackets themselves [, ]. ...

`How can I successfully publish an Angular2 Component to npm while keeping the templateUrl html file separate?`

I have embarked on the task of creating an Angular2 library that includes various Components. My goal is to package this library as an npm module, allowing me to easily install and utilize it in my other Angular2 projects using npm install. To achieve thi ...