I am using Angular 15 and ASP.NET Core 5. I get the paged items from backend when the pageSize
and pageIndex
are passed as parameters to it.
The action method that receives pageSize
and pageIndex
parameters then sends the paged items as well as totalCount
to frontend.
Here's that code:
[HttpGet("getPagedCommodities")]
public async Task<IActionResult> GetPagedCommodities([FromQuery] PagingParameters pagingParameters)
{
try
{
var commodities = await _repository.Commodity.GetAllCommoditiesAsync();
var totalCount = commodities.Count();
var pagedCommodities = await _repository.Commodity.GetPagedCommoditiesAsync(pagingParameters);
Response.Headers.Add("X-Pagination", JsonConvert.SerializeObject(totalCount));
return Ok(pagedCommodities);
}
catch
{
return StatusCode(500, "Internal server error");
}
}
In the frontend, this is the method that gets the paged items:
getPagedCommodities(pageSize: number, pageNumber: number): Observable<CommodityForList[]> {
let params: HttpParams = new HttpParams();
params = params.append('pageSize', pageSize);
params = params.append('pageNumber', pageNumber);
let httpOptions = {
params: params
};
return this.http.get<CommodityForList[]>(this.baseUrl '/getPagedCommodities/', httpOptions);
}
How can I read the totalCount
http header parameter sent from server?
Thank you for your help.
CodePudding user response:
You can pass the setting observe: 'response'
to the http get to observe the whole response and not just the body.
this.http.get(myUrl, {
observe: 'response',
params
}).subscribe(response => console.log(response))
So now instead of getting the body, you now get the whole response where headers
and body
is a property of that response:
{
headers: {
totalCount: 123
},
status: 200,
body: {}
}
CodePudding user response:
By using observe: 'response'
you receive HttpResponse<CommodityForList[]>
as a response and you can then access your header-values via response.headers.get("X-Pagination")
.
Your code could then look something like this:
getPagedCommodities(pageSize: number, pageNumber: number): Observable<{commodities:CommodityForList[], totalCount:string}> {
let params: HttpParams = new HttpParams();
params = params.append('pageSize', pageSize);
params = params.append('pageNumber', pageNumber);
const headers = new HttpHeaders({
observe: 'response'
});
const url = `${this.baseUrl}/getPagedCommodities/`;
return this.http.get<HttpResponse<CommodityForList[]>>(url, { headers, params })
.pipe(
map(response => {
// Access 'total count' in header:
const totalCount = response.headers.get("X-Pagination");
return { commodities: response.body ?? [],
totalCount: totalCount ?? '' };
})
);
}
Eventually you can access the returned values as follows:
this.getPagedCommodities(0, 1).subscribe(
res => {
console.log('Commodities-Array:', res.commodities);
console.log('Total count:', res.totalCount);
}
);