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>