angularurlpagination

Pagination - Page count from service


My service call is returning the data in this format:

items: [,...]
page: 1
pageSize: 30
totalCount: 3445

When I make this call, I am mapping the data in "items" array into the entity type.

getItems(pageNumber?: number): Observable<Item[]> {

        return this.http
            .get(this.itemsUrl + '?page=' + pageNumber)
            .map( (res) => {
                const body = res.json();

                return this.mapToItemList( body.items || {} );
            })
            .catch(this.handleError);
    }

I am adding pagination to display 30 records in each page. How do I get and return the "totalCount" without making another separate call? I am trying to display "Showing page x of total xx pages".

What is the best way to go about doing this?

Also, I want to pass the URL parameters in the below format, but it isn't working for me. What am I doing wrong?

const params: URLSearchParams = new URLSearchParams();
        if ( pageNumber ) {
            params.set('page', pageNumber.toString());
        }

Solution

  • You can have variable at service side and access it like below:

    public totalCount:any;    
    
    getItems(pageNumber?: number): Observable<Item[]> {
    
        return this.http
            .get(this.itemsUrl + '?page=' + pageNumber)
            .map( (res) => {
                const body = res.json();
                this.totalCount = body.totalCount; 
                return this.mapToItemList( body.items || {} );
            })
            .catch(this.handleError);
    }
    

    Component side:

    this.service.totalCount