Tips for obtaining response headers

Currently, I am utilizing Angular version 15.0 and retrieving a list of items from the backend (ASP.NET Core 5) with an additional item attached to the header. The GET method in the client-side service is as follows:

/** GET Paged commodities from the server ===============================*/
  getPagedCommodities(pageSize: number, pageNumber: number): Observable<CommodityForList[]> {
    let params: HttpParams = new HttpParams();
    params = params.append('pageSize', pageSize);
    params = params.append('pageNumber', pageNumber);

    const headers = new HttpHeaders({
      observe: 'response'
    });

    return this.http.get<CommodityForList[]>(this.baseUrl + '/getPagedCommodities/', { headers, params });

  }

This function sends two parameters to the server, retrieves a commodities list along with totalCount to facilitate paging, and sets the length property of mat-paginator. Additionally, the commodities list is set as an observable to enable dynamic search functionality for users. In the commoditiesList component, the code snippet for achieving this purpose is shown below:

 commoditiesForList$!: Observable<CommodityForList[]>;
 
this.commoditiesForList$ = this.commoditiesService.getPagedCommodities(this.pageSize, this.pageIndex+1);
 
this.commoditiesForList$.subscribe( res => {
      const totalCount = res.headers.get('X-Pagination');
    })

However, an error occurs stating:

Property 'headers' does not exist on type 'CommodityForList[]'.
Changing the type of commoditiesForList$ to
HttpResponse<CommodityForList[]>
may resolve the error, but it introduces a problem with receiving the commodities list as an observable. Is there a viable solution to obtain the commodities list as an observable while extracting the totalCount separately from the header? Your input is greatly appreciated.

Answer №1

For more details, visit https://angular.io/guide/http#reading-the-full-response

There may be additional information about the transaction that is not included in the response body. Servers sometimes send specific headers or status codes to signify certain conditions that are crucial to the application's workflow.

  getPagedCommodities(pageSize: number, pageNumber: number): Observable<HttpResponse<CommodityForList[]>> {
    // ...
    return this.http.get<CommodityForList[]>(this.baseUrl + '/getPagedCommodities/', { headers, params });
  }

You can access the content in the body attribute.

Also check out Angular: HttpClient read full response with Observable Array.

Answer №2

After reviewing your example, it is recommended to utilize the following configuration in your HTTP request:

{responseType: 'json', observe: 'events' }
. You can view a functional demonstration on stackblitz - one request

commoditiesForList$!: BehaviourSubject<CommodityForList[]>;
totalCount$!: BehaviourSubject<any>;

constructor(commoditiesService: CommoditiesService) {
this.commoditiesService.getPagedCommodities(this.pageSize, this.pageIndex+1).subscribe(res => {
  this.commoditiesForList$.next(res.body)
  this.totalCount$.next(headers.get('X-Pagination'))
})
}

Revised Answer

In your specific case, it is suggested to configure your HTTP request with these settings:

{responseType: 'json', observe: 'events' }
. An illustration of this setup can be found on stackblitz - two requests - shared pipe

Edit: To prevent dual requests, note that the GET request utilizes the share operator from rxjs. Special thanks to Arber for pointing this out.

getPagedCommodities(pageSize: number, pageNumber: number): Observable<CommodityForList[]> {
    let params: HttpParams = new HttpParams();
    params = params.append('pageSize', pageSize);
    params = params.append('pageNumber', pageNumber);

    const headers = new HttpHeaders({
      observe: 'response'
    });

    return this.http.get<CommodityForList[]>(this.baseUrl + '/getPagedCommodities/',
    { headers, params, responseType: 'json',observe: 'events'}).pipe(share());

  }

Upon implementation, data and headers can be accessed as displayed

 commoditiesForList$!: Observable<CommodityForList[]>;
 
this.commoditiesForList$ = this.commoditiesService.getPagedCommodities(this.pageSize, this.pageIndex+1).pipe(
    map((res) => (res as any).body));

this.totalCount$ =  this.commoditiesService.getPagedCommodities(this.pageSize, this.pageIndex+1).pipe(
    map((res) => (res as any).headers)), map(headers => headers.get('X-Pagination')));

Additional Resources: https://angular.io/guide/http#requesting-data-from-a-server

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

Tips for creating a typescript typeguard function for function types

export const isFunction = (obj: unknown): obj is Function => obj instanceof Function; export const isString = (obj: unknown): obj is string => Object.prototype.toString.call(obj) === "[object String]"; I need to create an isFunction method ...

Retrieve the initial occurrence that meets the conditions across three columns in MySQL

I am currently utilizing a NodeJS REST API that connects to a MySQL database. Within this database, there is a specific table we will refer to as Table_01: | C_0| C_1| C_2| C_3| | 1 | A1 | B1 | 1 | | 2 | A1 | B2 | 0 | | 3 | B1 | A1 | 0 | | 4 | A2 | ...

Material UI Date-Picker: Placeholder for Month Abbreviation with 3 Letters set as "MMMM" instead of the usual "MMM"

I'm currently using the most recent version of @mui/x-date-pickers (6.16.0). In my code snippet below, I have set the format of the text field input to be in "MMM DD, YYYY" style. However, when the date picker field is empty, the placeholder text disp ...

Making sure the checkbox stays selected in an angular environment

After experimenting with Angular 9 and a custom input, I achieved the following result => https://stackblitz.com/edit/angular-ivy-rgsatp My goal was to prevent users from disabling a radio button that is currently checked. Therefore, I made changes in ...

The specified element type is not valid: only a string (for built-in components) or a class/function is expected when attempting to display a component

`Unhandled Runtime Error Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you mi ...

Prevent Repeated Data Input in an Array using JavaScript

I am facing an issue where I need to ensure that the values being inserted are not repeated when performing a push operation. Below is the snippet of code in question: addAddress: function() { this.insertAddresses.Address = this.address_addres ...

What is the best way to filter through JSON data in Vue.js?

I'm encountering an issue with my JSON file that I am rendering to a table. I have 11 columns including id, name, and more. I want to search by every column, but the functionality only works for one column. If I try to filter the data multiple times, ...

What is the best way to first identify and listen for changes in a form

In Angular, there are reactive forms that allow you to track changes in both the complete form and specific fields: this.filterForm.valueChanges.subscribe(() => { }); this.filterForm.controls["name"].valueChanges.subscribe(selectedValue => { }); ...

What is the best way to verify the existence of an email address?

I'm currently using the jQuery validation plugin and everything is working fine, but I've hit a snag when it comes to checking email addresses. The issue is that the plugin returns either true or false based on whether the email exists or not. Ho ...

The "else" statement is never being executed

Trying to create a form where users enter their first name, last name, and city. If any input is empty or contains numbers, a message should appear requesting to fill out all boxes without numbers. Otherwise, display a personalized quote using the input in ...

Strategies for extracting data from a third-party website that utilizes JavaScript to set the value

Before, I would use jQuery to load external website content such as html or json. Sometimes, I even utilized a proxy PHP page in order to bypass strict origin policies on certain sites. However, I've encountered an issue with some websites. In the HT ...

Unable to retrieve DateTime.Now as a string within a Razor view

I am trying to retrieve the current time in a Razor View and utilize it in JavaScript, as demonstrated below: @{ string fileName = "Score_List_" + DateTime.Now.ToShortDateString(); } <script> // assigning C# variable to JavaScript variabl ...

Using http-proxy to forward request to a different port

In my code, I am creating a proxy that routes all application calls from port 3000 to port 3002 seamlessly. var http = require('http'), httpProxy = require('http-proxy'); var proxy = httpProxy.createProxyServer(); http.create ...

Hide all the div elements on the web page and only display one when a button is clicked

I have successfully set up a few buttons that can show and hide divs on click. However, I am wondering if it is possible to hide all other divs when one is showing, and also have "divone" show up on load. Buttons: <button class="btn btn-outline-primar ...

Attempting to craft a multi-filter feature using AngularJS that will allow for the precise filtering of JSON data based on both month and year identifiers

I have integrated AngularJS into the RoR framework and am working on creating a multi-filter for the "ng-repeat" function to filter JSON data based on "month_id" and "year_id". Here is the current code: JSON: [ { "date":"October 4, ...

Send a complex Json object in a POST request

Hey guys, I'm new to the world of web development and I've encountered a challenging issue. I have a complex object with numerous fields filled by a JavaScript function that needs to be passed to a C# HttpPost Call. I attempted to use JSON.Strin ...

PHP/AJAX user action history manager

Is there a library available that offers undo/redo functionality with a complete history for a web application? One possible solution could be a system using php/javascript/ajax where you can record the opposite action and variable state for each user acti ...

What is the best way to eliminate specific elements from an array of objects in MongoDB aggregate based on a condition?

I have a database of documents called ChatRooms stored in MongoDB with the following structure: { _id: ObjectId('4654'), messages: [ { user: ObjectId('1234'), sentAt: ISODate('2022-03-01T00:00:00.000Z') ...

Encountered an issue with setting the property of "something" to undefined when attempting to generate an array sorted by dates

After seeking help from @Kato on Stack Overflow regarding sorting a Firebase AngularFire array into weeks and days, I encountered an error where I cannot set a property of "something" that is undefined. To provide more context, I created a detailed Plunke ...

Exploring ViewChild Usage in Angular 8's Inheritance

I've encountered an issue with inheritance and ViewChild in a class where I always seem to get undefined. Let me simplify the problem for better understanding. First, let's look at the parent class: @Component({ selector: 'parent', ...