Requesting Next Page via Angular GET Method for Paginated API

Having trouble loading data from a paginated REST API using the code below. Any suggestions for a better approach are welcome!

component.ts

import { Component, OnInit } from '@angular/core';
import {HttpClient} from '@angular/common/http';


@Component({
  selector: 'app-test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.css']
})
export class TestComponent implements OnInit {

  articles: any[];
  url = 'https://example.zendesk.com/api/v2/users.json';

  
  constructor(private httpClient: HttpClient) { }

  ngOnInit() {
    this.fetchArticles(this.url, this.articles);
  }

  fetchArticles(url: string, articles: any[]) {
    this.httpClient.get(url).toPromise().then(response => {
      console.log(response['next_page']);
      if (articles === undefined) { articles = response['articles']; } else { articles = articles.concat(response['articles']); }
      console.log(articles);
      if (response['next_page'] != null) {
        this.fetchArticles(response['next_page'], articles);
      } else { console.log('End'); return articles; }
    });
  }

}

html

<ul *ngIf="articles">
  <li *ngFor="let article of articles">
    {{ article.title }}
  </li>
</ul>

Answer №1

It seems like the issue was resolved once I subscribed to the information. Everything is now working smoothly. Thank you for your assistance :)

import { Component, OnInit } from '@angular/core';
import {HttpClient} from '@angular/common/http';


@Component({
  selector: 'app-test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.css']
})
export class TestComponent implements OnInit {

  articles: any[];
  url = 'https://example.zendesk.com/api/v2/users.json';

  constructor(private httpClient: HttpClient) { }

  ngOnInit() {
    this.getArticles(this.url, this.articles);
  }

  getArticles(url: string, articles: any[]) {
    this.httpClient.get(url).subscribe(data => {
      if (articles === undefined) { articles = data['articles']; } else { articles = articles.concat(data['articles']); }
      if (data['next_page'] != null) {
        this.getArticles(data['next_page'], articles);
      } else { console.log('Finished'); }
      this.articles = articles;
    });
  }

}

Answer №2

I believe that the example I'm sharing is perfect for beginners.

api.service.ts!!!

import { Injectable } from '@angular/core';
import { HttpClient } from '@common/http';
import { Customer } from './customer';

@Injectable({
  providedIn: 'root'
})

export class ApiService {
 apiurl="https://reqres.in/api/users";

 constructor(private http:HttpClient) { }
 getConfig(){
   return this.http.get<Customer[]>(this.apiurl);
 }
}

The getConfig() function in the service above is being called in the component below. App.Component.ts!!!

    import { Component, OnInit } from '@angular/core';
    import { Customer } from './models/customer';
    import { ApiService } from './services/api.service';


    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    export class AppComponent implements OnInit {
      customers:any;
      title = 'ApiTable';
      constructor(private apiservice:ApiService){}
      ngOnInit(){
        this.customers=[];
        return this.apiservice.getConfig().subscribe(data =>this.customers = data['data']);
      }

Html!!!

    <h3 style="color: green;text-align: center;">DISPLAYING API DATA USING ANGULAR</h3>
    <div class="container">
    <table border="3px" class="table table-striped table-hover">
      <thead class="thead-dark">
... (Remaining content unchanged) ... 
    </table>
    </div>
    <router-outlet></router-outlet>

Answer №3

It seems that the issue lies in your implementation of the

getArticles(url: string, articles: any[])
function. Instead of updating the property of your component by using this.articles, you are manipulating the function parameters directly. To correct this, make sure to assign the response data to this.articles within the function as shown below:

  getArticles(url: string, articles: any[]) {
    this.httpClient.get(url).toPromise().then(response => {
      console.log(response['next_page']);
      if (this.articles === undefined) { this.articles = response['articles']; } else { this.articles = this.articles.concat(response['articles']); }
      console.log(this.articles);
      if (response['next_page'] != null) {
        this.getArticles(response['next_page'], this.articles);
      } else { console.log('End'); return this.articles; }
    });
  }

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

The Ionic serve command fails to recognize and reflect any saved changes, leading to a lack of automatic reloading

Recently, I encountered a strange issue while using my ionic 2 application. Whenever I execute the ionic serve command, it launches the server on localhost and produces the following output: [12:00:45] ionic-app-scripts 0.0.45 [12:00:46] watch started ...

What is the method for deducing the return type based on the parameter type in a generic function?

Check out this code snippet featuring conditional types: class X { public x: number; } class Y { public y: number; } type DataCategory = "x" | "y"; type TData<T extends DataCategory> = T extends "x" ? X : T extends "y" ? Y : ne ...

The issue arises when the desired image size is not reflected correctly on the background after changing

I've been working on a basic image slideshow where the background image changes based on user selection. However, I've noticed that when I change the image for the first time, the backgroundSize: cover property seems to disappear. Even if I try c ...

Tips for resolving the "trim" of undefined property error in Node.js

Looking to set up a basic WebAPI using Firebase cloud functions with express and TypeScript. Here's the code I have so far: import * as functions from 'firebase-functions'; import * as express from 'express'; const app = express( ...

Substituting generic type in inherited class method results in error message: "Property 'x' in type 'y' cannot be assigned to the property with the same name in the base class 'Parent'."

Here is the code snippet I am working with: class BaseModel { protected getAttribute<T extends BaseModel>(): keyof T | null { return null; } } class Payment extends BaseModel {} class Item extends BaseModel {} class Sale extends BaseModel { ...

"Embrace the powerful combination of WinJS, Angular, and TypeScript for

Currently, I am attempting to integrate winjs with Angular and TypeScript. The Angular-Winjs wrapper functions well, except when additional JavaScript is required for the Dom-Elements. In my scenario, I am trying to implement the split-view item. Although ...

Guide on utilizing mat-slide-toggle to assign either a value of 1 or 0

I am utilizing the mat-slide-toggle feature from Material in a similar manner to this example https://material.angular.io/components/slide-toggle/overview The problem I am encountering is similar to the issue outlined in this link: https://stackblitz.com ...

Which is better: Utilizing ASP.NET Core or ASP.NET Core MVC in tandem with Angular for the

Currently in the planning stages of developing a website or web application using .NET Core for the backend and Angular for the frontend. One aspect that is proving to be confusing is whether to use ASP.NET Core or ASP.NET Core MVC on the backend. I'm ...

Issue with starting @mauron85/cordova-plugin-background-geolocation on Ionic 5 and Angular 9 platform

I'm facing a challenge with integrating the background geolocation plugin into my app. Here is the documentation link for reference: https://ionicframework.com/docs/native/background-geolocation Here's the snippet of my code that initiates the p ...

The parameter 'CallHistoryMethodAction<[string, unknown?]>' does not match the 'UserActionType' parameter

Using a development environment with React, TypeScript, and connected-react-router. My Intention: I aim to utilize the router action asynchronously within the user action. After successful login, I want the application to navigate to the main screen. Err ...

Multiple invocations of the callback function in an Angular5 template binding

In trying to create a grid component that uses structured data containing definitions for columns and an array of data. Each column definition includes a callback function to customize the display of that specific column's value. Within each callbac ...

Tips for executing a code after a Firestore .update() operation is completed on the server side in Angular

When a user logs in, I want to send a locally generated token to be stored in both localstorage and firestore. The user is then routed to the admin component. In the app component, I will subscribe to the user and compare the stored token with the one in ...

Best practice for incorporating types into a Redux-toolkit reducer

As someone who is relatively new to TypeScript, I have a specific goal in mind. I am looking to create an interface where: interface ActionType { fieldName: {any one key from the interface FormStateType listed below such as 'name', 'age&ap ...

Leveraging JSON data in subsequent GET request in Ionic 3

My application receives input, concatenates it to a string, and then requests JSON data. The response includes the following first two lines: Now, I need to update my code to be asynchronous. It should make the initial call, wait for a response, retrieve ...

Having trouble retrieving the URL from the router in Angular 2?

Whenever I try to access the URL using console.log(_router.url), all it returns is a / (forward slash). Here is the code snippet in question: constructor( private el: ElementRef, private _auth:AuthenticationService, @Inject(AppStore) private ...

Incorporate a generic type into a React Functional Component

I have developed the following component: import { FC } from "react"; export interface Option<T> { value: T; label: string; } interface TestComponentProps { name: string; options: Option<string>[]; value: string; onChang ...

Expanding constructor in TypeScript

Can the process described in this answer be achieved using Typescript? Subclassing a Java Builder class This is the base class I have implemented so far: export class ProfileBuilder { name: string; withName(value: string): ProfileBuilder { ...

Surprising Denials Following the Launch of Karma Using NgUpgrade

Currently in the process of implementing ngupgrade into our AngularJS application and consistently encountering unexpected rejection errors while Karma is initializing. The functionality of my app with ngupgrade is running smoothly, but the issue lies wit ...

Can you explain the distinction between employing 'from' and 'of' in switchMap?

Here is my TypeScript code utilizing RxJS: function getParam(val:any):Observable<any> { return from(val).pipe(delay(1000)) } of(1,2,3,4).pipe( switchMap(val => getParam(val)) ).subscribe(val => console.log(val)); ...

Utilizing Sequelize with Typescript for referential integrity constraints

After defining these two Sequelize models: export class Users extends Model<Users> { @HasMany(() => UserRoles) @Column({ primaryKey: true, allowNull: false, unique: true }) UserId: string; @Column({ allowNull: false, unique: tru ...