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?