puddlejumper26 / blogs

Personal Tech Blogs
4 stars 1 forks source link

Observable 2 layers #182

Open puddlejumper26 opened 3 years ago

puddlejumper26 commented 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.

// 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>