Retrieving Headers from a POST Response

Currently, I am utilizing http.post to make a call to a .NET Core Web API.

One issue I am facing is the need to extract a specific header value from the HTTP response object - specifically, the bearer token. Is there a method that allows me to achieve this?

var user = this.http
        .post<User>(this.loginUrl, body, { 'headers': headers })
        .pipe(map(user => {
           //processing user data logic goes here
            return user;
        }))

Answer №1

By utilizing an anonymous object within the options parameter with the observe property set to response, I successfully gained access to the response headers when using the POST method in the Web API:

    const httpOptions: { headers; observe; } = {
        headers: new HttpHeaders({
            'Content-Type':  'application/json'
        }),
        observe: 'response'
    };

    var user = this.http
        .post<User>(this.loginUrl, body, httpOptions)
        .pipe(map(event => {
            //Checking for the HttpEventType is not strictly necessary
            if (event.type == HttpEventType.Response)
            {
                let user = event.body;
                let headers = event.headers
                //Perform operations with user data and headers
                return user;
            }
        }))

The HttpEvent then allows access to the headers and body as properties.

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

The modal remains closed: Error - Attempting to access property 'open' of undefined

I've been attempting to showcase a pop-up that I implemented as a modal, but I keep getting this error: TypeError: Cannot read property 'open' of undefined The pop-up was created as a component: import { Component, OnInit, ViewChild, Ele ...

Displaying a pair of items side by side using Angular's ngFor

I've encountered an issue with my code related to displaying a 4 by 8 grid using the ngFor command. Below is the snippet of the code in question: <div cdkDropList class="example-list" (cdkDropListDropped)="drop($event)"> <ng-cont ...

"Troubleshooting: Module not found" (Getting started with Jest in a nested project connected to a shared directory)

I've recently taken over a project that contains the following folder structure: node_modules/ server/ ├── node_modules/ ├── src/ │ └── helpers/ │ ├── updateTransactions.ts │ └── updateTransactions.tes ...

What could be the reason for typescript not issuing a warning regarding the return type in this specific function?

For instance, there is an onClick event handler attached to a <div> element. The handler function is supposed to return a value of type React.MouseEventHandler<HTMLDivElement> | undefined. Surprisingly, even if I return a boolean value of fal ...

The use of Next.js v12 middleware is incompatible with both node-fetch and axios

I am facing an issue while developing a middleware that fetches user data from an external endpoint using Axios. Surprisingly, Axios is not functioning properly within the middleware. Below is the error message I encountered when using node-fetch: Module b ...

Navigating with Angular inside an HTTP POST Observable and subscription

Whilst attempting to guide a user towards a dashboard within the response of an httpClient.post request, I have encountered a peculiar issue. The page navigates "successfully" (as evidenced by the URL bar) but unfortunately, most elements of the components ...

When a user reverts UI changes to their original values in Angular reactive forms, does the pristine state reset?

I need the Submit button in my form to only be enabled when there is a change in the input. If the values in the form controls remain unchanged, the Submit button should be disabled. Initially, I attempted to utilize the FormGroup.pristine flag for toggl ...

Angular 4 allows you to assign unique colors to each row index in an HTML table

My goal is to dynamically change the colors of selected rows every time a button outside the table is clicked. I am currently utilizing the latest version of Angular. While I am familiar with setting row colors using CSS, I am uncertain about how to manip ...

An error has occurred: Unable to access the 'group_status' property of an undefined console object

I have been encountering a persistent error in the console, with it continuously increasing. The issue arises when I utilize two-way binding with ngModel alongside an interface. To provide further insight, I have included screenshots of my code below. Scr ...

Is there a way to tally up the overall count of digits in a number using TypeScript?

Creating a number variable named temp in TypeScript: temp: number = 0.123; Is there a way to determine the total count of digits in a number (in this case, it's 3)? ...

Variations in key options based on specific situations

Is it possible to make certain keys required in Typescript depending on the circumstances? For instance interface IDog { name: string; weight: number; } class Retriever implements IDog { name = "Dug"; weight = 70; public updateAttribute(props ...

When utilizing destructuring in React.js with TypeScript, incorrect prop values are not being alerted as expected

I recently started using TypeScript and I have been enjoying it so far. However, I came across an issue today that I couldn't solve. Imagine a scenario where a parent component A passes a function that expects a numeric value to the child component B ...

The React Functional Component undergoes exponential re-renders when there is a change in the array

I'm encountering a problem with one of my functional components. Essentially, it maintains an array of messages in the state; when a new message is received from the server, the state should update by adding that new message to the array. The issue ar ...

Tips on personalizing the formatting alert in Webclipse for Angular 2 using Typescript

Webclipse offers extensive formatting warnings for TypeScript code, such as detecting blank spaces and suggesting the use of single quotes over double quotes. However, some users find the recommendation to use single quotes annoying, as using double quotes ...

Passing events from a parent component to dynamically created child components in Angular

UPDATE: I've decided to tackle this issue in a different way by retrieving dynamic child component values in the parent component's save() function, following the accepted answer. I am attempting to create a system where a parent component emits ...

Guide on transferring information obtained from a service to an Angular datatable

Recently, I started working on Angular 4 and encountered an issue while trying to display data from an Angular service in JSON format using angular-datatable. Despite trying various options, I am unable to get the data to display within the columns of the ...

Nuxt SSR encounters issues when modifying data variables

There is an issue with my Nuxt app where sometimes when the page loads, I encounter an error in the console that causes the page to stop loading other components. The error message reads: Cannot read properties of undefined (reading 'resolved') ...

In Vue3, using the script setup feature allows for setting default property values within nested objects

I am developing a component that is designed to accept an object as a prop. In case the object is not provided, I aim to set a default value for it. <script setup lang="ts"> interface LocaleText { text: string; single?: boolean; coun ...

What is the best way to perform type checking for a basic generic function without resorting to using a cumbersome cast

Struggling with TypeScript and trying to understand a specific issue for the past few days. Here is a simplified version: type StrKeyStrVal = { [key: string]: string }; function setKeyVal<T extends StrKeyStrVal>(obj: T, key: keyof T, value: str ...

Filter that caters to specific number of properties of X

Looking to create a versatile filter function that can handle multiple criteria? Here's a snippet of the current filtering function: const filterRows = () => { items.filter((item) => { if(selectedDrinks.length > 0 && select ...