Unexpected Behavior: Angular App Retrieving Entire Collection, Instead of Limited Number of Results

Incorporating observables in my Angular application to fetch data from our API has been a challenging task. Due to the substantial amount of data to be retrieved, we implemented ng2-pagination for efficient pagination handling. The objective was to load specific data for each page as it is accessed. For instance, on the initial page load, we aimed to retrieve the first 15 results and subsequently load data relevant to subsequent pages upon user interaction.

When I tested the API call using Postman, I received an expected limited set of results instead of the entire collection, confirming its functionality.

However, when integrating this API call with the observable utilized in the Angular app, I encountered an issue where the entire collection was still being pulled.

This is the snippet of code representing the API call (where 'page' represents the page number and 'pagesize' denotes the number of results per page):

getByCategory(category: string, page, pagesize) {
    const q = encodeURIComponent(stage);
    return this.http.get
    (`https://api.someurl.com/${this.ver}/clients/category/${q}?apikey=${this.key}&page=${this.page}&pagesize=${this.pagesize}`)
        .map((response: Response) => response.json())
        .catch(this.stageErrorsHandler);
}
stageErrorsHandler(error: Response) {
    console.error(error);
    return Observable.throw(error.json().error || 'Server error');
}

Within my component, I subscribed as follows, requesting page 1 with 12 results returned:

ngOnInit() {
   this.clientService.getByCategory('consulting', 1, 12)
        .subscribe(resRecordsData => {
            this.records = resRecordsData;
            console.log(this.records);
        },
        responseRecordsError => this.errorMsg = responseRecordsError);
}

In the view, I iterated over the array and passed items through the pagination pipe like so:

<tr *ngFor="let record of records.data | paginate: { id: 'clients', itemsPerPage: 12, currentPage: page, totalItems: records.count }">

    <pagination-controls class="paginator" (pageChange)="page = $event" id="clients"
            maxSize="15"
            directionLinks="true"
            autoHide="true">
    </pagination-controls>

It's worth noting that the API call provides the total count along with the array of objects, which is crucial for the pagination tool to determine the number of pages to load. The API response structure includes 'data' as the collection of records and 'count' as the total number of records:

{
  "count": 10438,
  "data": [
    {
      "id": "someId",
      "name": "someName"
    }
      ]

Despite expectations, when I console log (this.records) within the ngOnInit lifecycle, the output displays the full collection rather than a finite list of 12 results:

Object {count: 10728, data: Array(4037)}

The discrepancy between the expected behavior and the actual outcome leaves me puzzled. While the API call works fine in Postman, the integration with the observable seems to fall short. Any insights on potential oversights or errors in how I am utilizing the observable?

Answer №1

Have you checked out the service call URL in Chrome dev tools' network tab? Is your URL template displaying correctly as:

https://api.someurl.com/${this.ver}/clients/category/${q}?apikey=${this.key}&page=${this.page}&pagesize=${this.pagesize}

Make sure to reference the parameters (category: string, page, pagesize) without using "this." - for example, use ${page} instead.

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

How can the `!` operator be utilized in MikroORM Typescript entities?

How can I declare a key in a JS object with an ! before the colon? MikroORM syntax for class @Entity() export class Post { // Using @PrimaryKey() decorator to designate primary key @PrimaryKey() id!: number; @Property({ type: "date", de ...

Checking CSV File Validity Using JavaScript

Is there a way to verify if a text box contains comma-separated values and display an alert if it does not? Additionally, the values should be characters like A,B,C,D function checkValues() { //validate text box; } <input type=" ...

How can we store image file paths in MongoDB?

I'm currently working on developing a REST API using nodeJS, express, mongoose, and mongodb. I have successfully implemented file uploads with multer and saved the files to a folder. Now, I need to save the path of the uploaded file to a mongodb docum ...

Issue with my lazyloading extension for Mootools

Seeking to create a plugin for sequential image downloads using MooTools. Assuming there are images with the img tag inside a div with the class imageswrapper. The goal is to download each image in order, one after the other until all images are loaded. ...

Displaying a JSON response on an HTML webpage

JSON object: {"id":75,"year":2011,"make":"Aston Martin","model":"V12 Vanquish"} jQuery: function post() { $("form").on("ajax:success", function(e, data, status, xhr) { var json = JSON.parse(xhr.responseText); $.each(json, function(k, v) { ...

Managing a webpage using Xcode and Swift's UIWebView

Recently, I developed a straightforward application that guides users to a web-based platform. One of the app's pages allows users to search for store stock from various stores by manually inputting the store number or utilizing automatic location det ...

Angular routing and parameters are not functioning as expected

In my code, I have implemented the following controller: app.controller('ObjectBoardCtrl', ['$scope' , '$rootScope' , '$routeParams' , function($scope , $rootScope, $routeParams) { $scope.selectedObjectId = $ ...

What is the best way to utilize Object.keys() for working with nested objects?

When working with nested objects, I am trying to access the properties using Object.keys() and forEach(). However, I am encountering an issue when attempting to access the nested keys filteringState[item][el]. Is there a specific way to write a function f ...

Enrolling a new plugin into a software repository

I have 5 unique classes: ConfigManager ForestGenerator TreeCreator NodeModifier CustomPlugin My goal is to create an npm module using TypeScript that incorporates these classes. The main feature I want to implement is within the ConfigManager clas ...

Guide on using javascript to alter a json structure

Recently, I discovered a method to manipulate a JSON file using JavaScript. Although I don't have any formal training in JavaScript, I understand that it is primarily utilized on web browsers. Can someone guide me on how to execute this script? I cons ...

Guide on enabling a plugin for Stylus in a Vue 2 project using the webpack template

I am working on a Vue2 project with the Webpack template and utilizing Stylus as a CSS preprocessor. I'm facing difficulties in applying plugins for Stylus like rupture. I attempted to adjust the options in build/utils.js for the stylus loader by add ...

Unable to conduct end-to-end testing as Nestjs fails to resolve dependencies

I encountered the following error : Nest is unable to resolve dependencies of the ParametrageRepository (?). Please ensure that the argument DataSource at index [0] is available in the TypeOrmModule context. This is my test code : describe("ParametrageC ...

Exploring Angular 2 testing with TypeScript: multiple occurrences of specifications in Jasmine

Recently, I followed a tutorial on testing an Angular 2 application which can be found at: https://angular.io/docs/ts/latest/guide/testing.html Upon completing the 'First app test' section and moving to 'unit-tests.html', I noticed tha ...

Obtaining req.body twice while handling a 307 redirect in an Express application

I have encountered a unique issue with my form submission in an express js application. Upon form submission, data is being POST to another route and then redirected back to the original route. View <form action="action" method="post> <input t ...

Implementing dynamic element selection with jQuery: combining onClick and onChange events

I am looking to update the appearance of the arrow on a select option. By default, it is styled as caret-down. When a user clicks in the input area, I want to change the style to caret-up. If the select option has been changed or no action has been taken, ...

When executing npm run build for production, the resulting build does not include distribution for

I am encountering an issue with my Angular project, specifically during the build process. After running ng build, the dist folder is created with the correct build. However, when I run the command: ng build --prod it generates the production build as e ...

Reacts Router Link does not refresh page content

My React and Redux application features a Movie component that displays movie data fetched from an API. To enhance user experience, I decided to create a Similar Movies section at the bottom of the page. This section contains components that allow users t ...

Is there a way to display a secondary header once the page is scrolled down 60 pixels?

.nav-header2{ background: purple; display: flex; justify-content: center; align-items: center; } .header2-container{ width: 68vw; height: 60px; padding: 0 2vh; border: 1px solid red; ...

What is the best way to enable an element to be dragged from just a single point?

I am facing a challenge with a parent div (such as "#strip17") that contains multiple child divs. Most of these child divs consist of a canvas where the user can draw using their mouse. However, the last child div should act as a handle that allows the use ...

Tips for importing font files from the node_module directory (specifically otf files)

We cannot seem to retrieve the fonts file from the node module and are encountering this error message. Can't find 'assets/fonts/roman.woff2' in 'C:\Projects\GIT2\newbusinessapp\projects\newbusinessapp\src ...