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

How can I use Angular2 to draw a square [input] number of times?

I need to create a specific number of squares within a container using Angular2. Can you please provide me with a straightforward example, preferably utilizing canvas? Currently, I have converted webpack starter for use with Angular: This is the code ins ...

Accessing the various types within a monorepo from a sibling directory located below the root folder

Seeking assistance in resolving a referencing types issue within a TypeScript monorepo project. Unsure if it is feasible given the current setup. The project structure is as follows: . ├── tsconfig.json ├── lib/ │ └── workers/ │ ...

Tips for building an effective delete function in Angular for eliminating a single record from a table

I've been working on creating a method to delete an employee by their ID, and I've tried various approaches in my VS Code. Unfortunately, all of them have resulted in errors except for this specific method. Whenever I click on the delete button, ...

What is the mechanism behind the widening of object literal types in Typescript inference?

I've been reading up on how typescript broadens inferred types but I'm still not entirely clear about what's happening here: type Def = { 'T': { status: 5, data: {r: 'm'}}, } function route<S extends keyof Def> ...

What improvements can I implement in this React Component to enhance its efficiency?

Seeking advice on improving the efficiency of this React Component. I suspect there is code repetition in the onIncrement function that could be refactored for better optimization. Note that the maxValue prop is optional. ButtonStepper.tsx: // Definition ...

How can I implement a recursive nested template call in Angular 2?

Hopefully the title isn't too misleading, but here's my dilemma: I am in the process of building an Angular 2 app and utilizing nested templates in multiple instances. The problem I am facing involves "widgets" within my app that can contain oth ...

Troubleshooting notifications generated by react-hook-form and zod

My customer registration form is causing all my error messages to show as "required." I suspect it might be a misconfiguration in zod or react-hook-form. Below, you'll find the code snippets. This is my generic input component: import { DetailedHTMLP ...

How can I use regex within a pipe to split a string in Angular 4?

I need to implement a method where I can split a string based on special characters and spaces in the given regex format, excluding "_". Example: #abc_xyz defgh // output #abc_xyz Example: #abc@xyz defgh // output #abc Example: #abc%xyz&defgh // out ...

When the next() function of bcrypt.hash() is called, it does not activate the save method in mongoose

Attempting to hash a password using the .pre() hook: import * as bcrypt from 'bcrypt'; // "bcrypt": "^1.0.2" (<any>mongoose).Promise = require('bluebird'); const user_schema = new Schema({ email: { type: String, required: tru ...

Is there a way to reverse the animation playback in Angular?

I am working on an animation that involves a box fading from its original color to yellow. However, I would like to achieve the opposite effect: when the page loads, I want the box to start off as yellow and then fade back to its original color. The challe ...

How can I disable AngularJS code completion/suggestion feature in VS Code?

Currently, I have made the switch from AngularJS to Angular 6. However, despite this change, VS Code continues to offer me AngularJS code suggestions. https://i.stack.imgur.com/XerhF.png The syntax presented in the first suggestion is for AngularJS while ...

Turn off slider trace animation?

Check out the slider component in MUI here: https://mui.com/material-ui/react-slider/ I'm currently exploring how to disable the animation on the nub so it moves instantly to the new position. Any advice on how to achieve this? ...

Implementing interactive dropdown menus to trigger specific actions

I have modified some code I found in a tutorial on creating hoverable dropdowns from W3. Instead of the default behavior where clicking on a link takes you to another page, I want to pass a value to a function when a user clicks. Below is a snippet of the ...

How can I manually listen to Angular 2 events on a dependency injected instance?

Assume I am working with a component: @Component({selector: 'todo-cmp'}) class TodoCmp { @Input() model; @Output() complete = new EventEmitter(); // TypeScript supports initializing fields onCompletedButton() { this.complete.next(); / ...

"Observables in RxJs: Climbing the Stairs of

Previously, I utilized Promise with async/await syntax in my Typescript code like this: const fooData = await AsyncFooData(); const barData = await AsyncBarData(); ... perform actions using fooData and barData However, when using RxJs Observable<T> ...

Issue encountered while declaring a variable as a function in TSX

Being new to TS, I encountered an interesting issue. The first code snippet worked without any errors: interface Props { active: boolean error: any // unknown input: any // unknown onActivate: Function onKeyUp: Function onSelect: Function onU ...

ASP.Net Core 3.1 server receives a blank user in JWT Bearer token

Today, I've been working on integrating JSON Web Token information with HttpContext.User using the Microsoft.AspNetCore.Authentication.JwtBearer library. The Issue: Whenever I make a request to the server, I can access functions with the [Authorize] ...

The React Component in Next.js does not come equipped with CSS Module functionality

I have been attempting to incorporate and apply CSS styles from a module to a React component, but the styles are not being applied, and the CSS is not being included at all. Here is the current code snippet: ./components/Toolbar.tsx import styles from & ...

How to generate a new array in Angular by combining elements from two existing arrays for common items

I am currently working on a TypeScript function to compare two arrays and generate a third array containing the common items. For example: employees: any; offices: any; constructor() { this.employees = [ { fname: "John", lname: "James", sta ...

Transferring data from a parent ng-template to a child ng-template

Is it possible to nest one ng-template inside another ng-template? If so, how can I pass data from the parent ng-template to its child ng-template? I have tried several methods, but none of them seem to work for me. <ng-template let-r="result" #rt&g ...