Retrieve an additional 10 items from the API when the button in the Angular list is clicked

I need to display 10 items each time the button is clicked.
Below is the code snippet for the services:

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


@Injectable({
  providedIn: 'root'
})
export class StudentDataService {

  url = "https://dummyjson.com/users?limit=10";

  // Constructor / Instance
  constructor(private http: HttpClient) { }
  getdata(){
    return this.http.get(this.url)
  }
}

Here is the HTML/Bootstrap Code:
There is a load more button at the bottom which should display 10 more items every time it is clicked.

<table class="table table-striped">
  <thead>
    <tr>
      <th scope="col">#ID</th>
      <th scope="col">First Name</th>
      <th scope="col">Last Name</th>
      <th scope="col">Age</th>
      <th scope="col">Gender</th>
      <th scope="col">User Detail</th>
      <th scope="col">Add To Favorite</th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let user of newdata.users">
      <td>{{ user?.id }}</td>
      <td>{{ user?.firstName }}</td>
      <td>{{ user?.lastName }}</td>
      <td>{{ user?.age }}</td>
      <td>{{ user?.gender }}</td>
      <td>
        <button type="button" class="btn" (click)="UserClicked(user)">
          See Details
        </button>
      </td>
      <td (click)="moveToFavorite(user)">
        <button class="btn-fav">Add To Favorite</button>
      </td>
    </tr>
  </tbody>
</table>
<div class="btn-div">

  <button class="load-more ">Load More</button>
</div>

Answer №1

To make your "Load More" button functional, ensure that you include a click event that triggers the loading of more users.

<button class="load-more" (click)="loadUsers()">Load More</button>

Keep track of the number of users to be loaded with a variable called limit. Each time the loadUsers function is called, increment the limit value by 10. Send this updated limit value to the getData method within the StudentDataService service. Also, ensure that the newData is updated once the observable returns the data.

limit: number = 10;

loadUsers() {
  this.limit += 10;
  this.studentDataService.getdata(this.limit)
    .subscribe({
      next: (resp) => {
        this.newdata = resp;
      }
    })
}

Within your StudentDataService, modify the getdata function to accept the limit parameter and include it in the URL as a query string.

export class StudentDataService {

  url = "https://dummyjson.com/users";


  getdata(limit: number = 10) {
    return this.http.get(this.url + `?limit=${limit}`);
  }
}

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

Error: Unable to retrieve URL from environment variable UPSTASH_REDIS_REST_URL in the parsing process

Encountering an issue with TypeScript while attempting to create a new Redis instance. I've set up an .env.local file with matching names for the redis URL and token. import { Redis } from '@upstash/redis' export const db: Redis = new Redis ...

Angular 2: Simplifying the Process of Retrieving a Full Address Using Latitude and Longitude

Currently, I am utilizing the angular 2-google-maps plugin. Is there a way to retrieve the country and postal code based on latitude and longitude using Angular 2 Google Maps with Typescript? ...

Finding the total of values within an array in Angular 2 and Ionic 2 by utilizing *ngfor

As I work on developing a mobile application using Ionic 2, my current task involves calculating the total allocation sum (Course.allocation) for each year per horse in the database. For instance: Table: Course (Race): [Id_course: 1, allocation: 200, dat ...

Stay Alert: Angular Observable Continuously Monitored for Promise Updates

I am currently working on an angular application that has a connection with a printer. The printer possesses its own status service that is implemented as a promise, providing the printer's current status as a response. However, I am facing an issue w ...

Understanding the concept of a "class variable" in Typescript when referring to a variable that belongs to another class

When we declare a variable at the class level and assign it the type of another class, such as in the following code: let greeter: Greeter; //line 1 greeter = new Greeter("world"); What is contained within 'greeter' on line 1? ...

Troubleshooting Problem in Angular 6: Difficulty in presenting data using *ngFor directive (data remains invisible)

I came across a dataset that resembles the following: https://i.sstatic.net/S0YyO.png Within my app.component.html, I have written this code snippet: <ul> <li *ngFor="let data of myData">{{data.id}}</li> </ul> However, when I ...

Exploring Angular 2: Incorporating multiple HTML pages into a single component

I am currently learning Angular 2 and have a component called Register. Within this single component, I have five different HTML pages. Is it possible to have multiple templates per component in order to navigate between these pages? How can I implement ro ...

Why is the function not being called when declaring a variable, resulting in a type error?

click here reference: const fn1 = (arg1: { key: number, })=>{ console.log(arg1) } fn1({ key: 1 }) const data = { key: 1, a: 1, } fn1(data) fn1({ key: 1, a: 1, }) more info Assistance needed: Why is ...

Encountering a type 'any' issue with the Authentication guard injection in Angular 17

I implemented a functional guard in Angular 17 import { Inject } from '@angular/core'; export const checkoutGuard: CanActivateFn = (route, state) => { const customerService = Inject(CustomerService); const router = Inject(Router); ...

Transferring css to an external file within an angular 4 component by utilizing webpack

I encountered this specific error message: Error: Anticipated 'styles' to be a collection of strings. Despite the fact that I have clearly defined the styles as an array of strings: styleUrls: ['./app.component.css'] Can anyone pinp ...

Guide to setting up value observation in React Context for optimal functionality

Imagine a scenario where there is a Parent Component that provides a Context containing a Store Object. This Store holds a value and a function to update this value. class Store { // value // function updateValue() {} } const Parent = () => { const ...

Typescript typings for child model/collection structures

I have encountered an issue while trying to implement a Model/Collection pattern with various typings. Both the Model and Collection classes have a method called serialize(). When this method is called on the Collection, it serializes all the Model(s) with ...

Extending a Svelte component with a P5JS class: A step-by-step guide

As a newcomer to SO, I haven't asked many questions before, so please bear with me if I don't entirely follow the guidelines. I'll do my best to explain the issue at hand. In my project, I am utilizing Sveltekit (create-svelte) and P5JS (p5 ...

Incorporate JavaScript Library into StencilJs Using TypeScript

Recently, I decided to incorporate a JavaScript library called Particles.js into my project. The process involved importing it and initializing it within my component: import { Component, h } from '@stencil/core'; import * as particlesJS from &a ...

What is the most efficient way to convert a JSON object into a URL search parameter using as few characters as possible?

Challenge: On my web app, users can adjust settings to create or edit generative artworks and then share their creations via a shortened link. The objective is to store all the data needed to replicate the artwork in the URL within 280 characters. Initia ...

Enter the newest addition of the node.js layer that bridges the gap between user interface and

Currently, I am in the process of creating a solution on AWS that relies on Cognito for managing users. To kickstart this project, I have referenced the SAAS QuickStart guide available at: SAAS QuickStart However, I am making a significant change by aim ...

Exploring the power of TypeScript for authenticating sessions with NextJS

Utilizing next-auth's getSession function in API routes looks something like this for me: const mySession = await getSession({ req }); I have confirmed that the type of the mySession is outlined as follows: type SessionType = { user: { email: s ...

Utilize CSS Styles with Angular 2 Component Selectors

I'm currently diving into Angular 2 and I've been pondering the idea of implementing CSS styles using the component selector in this manner: the component @Component({ selector: 'app', styleUrl: './local.css', te ...

Transmitting messages from a cross-domain iframe to the parent window

In my parent component, I am embedding an iframe from a different domain. The iframe contains a button that when clicked, I need to capture the event and pass it back to the parent component. I have experimented with using window.postMessage and window.ad ...

The function of type 'PromiseConstructor' is not executable. Should 'new' be added? React TypeScript

.then causing issues in TypeScript. interface Props { type: string; user: object; setUserAuth: Promise<any>; } const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => { e.preventDefault(); if (type === "signup" ...