This is my page.ts
export class CharactersPage {
url: string = "https://rickandmortyapi.com/api/character?page=1";
chars: any;
constructor(private http: HttpClient) {
this.getInfo();
}
async getInfo() {
this.http.get<any>(this.url).subscribe(res => {
this.chars = res.results
});
}
}
This is my page.html
<ion-content>
<ion-list>
<ion-item *ngFor="let chars of chars | filter:searchTerm" id="item">
<ion-thumbnail slot="start">
<ion-img src="{{ chars.image }}"></ion-img>
</ion-thumbnail>
<ion-label>{{ chars.name }}</ion-label>
</ion-item>
</ion-list>
</ion-content>
What i get using this code is the first 20 characters. I want to be able to print all the characters without having to make a different request everytime. The are in total 42 pages with 20 characters on each(except the 42th which only has 6). I tried using while loop but angular keeps crashing on me.
CodePudding user response:
Maybe you could try joining (combine) the requests into one using rxjs combineLatest.
So do something like a "https://rickandmortyapi.com/api/character?page=pageId"
and iterate the pages you want then combine the observables into one.
const url ='https://rickandmortyapi.com/api/character?page=';
const pages = ['1','2','3','4','5'];
const observables = pages.map(pageId => this.http.get<any>(this.url pageId));
combineLatest(observables).pipe(map(values) => ({...values})).subscribe(res => {
this.chars = res.results
});
Note this will still result in multiple requests. If you want a single request the api must be able to handle it.
Also, the function getInfo
is not async
CodePudding user response:
Based on ducumentation https://rickandmortyapi.com/documentation/#info-and-pagination the api supports some kind of pagination and you will have to implement custom one. Making 42 sequential request its not an option to my opinion.
You can check these two links with prev/next buttons implementation:
.