Issue
I want to load 10 items every time click on the button.
Here is the services code:
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)
}
}
HTML/Bootstrap Code is here:
There is a button at the bottom you can see the load more. As I set the limit 10 in the API, but I need to load 10 more list every time on button click.
<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>
Solution
For your "Load More" button, you should have a click event to load users.
<button class="load-more" (click)="loadUsers()">Load More</button>
You should have a variable to track the limit
. When the loadUsers
is called, the limit
should be added by 10. And pass the limit
to the getData
in the StudentDataService
service. Also you should update the newData
when the observable is returned.
limit: number = 10;
loadUsers() {
this.limit += 10;
this.studentDataService.getdata(this.limit)
.subscribe({
next: (resp) => {
this.newdata = resp;
}
})
}
In your StudentDataService
, the getdata
function should have an argument to receive the limit
and pass it into the URL as the query string.
export class StudentDataService {
url = "https://dummyjson.com/users";
getdata(limit: number = 10) {
return this.http.get(this.url + `?limit=${limit}`);
}
}
Answered By - Yong Shun
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.