Open puddlejumper26 opened 3 years ago
Assume the I need the results.name part. but the data is in serveral url with different page number, starting from 1, then 2,3,4,5.. And i need to use the 'next' to obtain the next page, when 'next': null, then this is the last page.
'next': null
// now is http://swapi.dev/api/planets/?page=1 { "next": "http://swapi.dev/api/planets/?page=2", "previous": null, "results": [ { name: planet1 } { name: planet2 } { .... } ] }
type Planet = { name: string; } type Data = { next: string; results: Planet[]; } url = 'http://swapi.dev/api/planets/?page=1'; getData(url: string = this.url):Observable<Data>{ return this.http.get(url) .pipe(map((res: {next: string, results: Planet[]})=>{ return { next: res.next, results: res.results, } }) }
then in the target component, I need to subscribe the getData method
url = 'http://swapi.dev/api/planets/?page=1'; planets=[]; getPlanets(url: string = this.url){ this.getData(url).subscribe( res => { this.url = res.next; this.planets.push(...res.results); console.log('11111111', this.planets); console.log('22222222', this.url); if(this.url !== null) {this.getPlanets(this.url)}; }) }
then I could display all the name of planets on the template.
<div *ngFor = let item of planets>{{item.name}}</div>
Assume the I need the results.name part. but the data is in serveral url with different page number, starting from 1, then 2,3,4,5.. And i need to use the 'next' to obtain the next page, when
'next': null
, then this is the last page.then in the target component, I need to subscribe the getData method
then I could display all the name of planets on the template.