Multiple GET requests with Angular 4/5

0

I'm doing a query in an API (SWAPI). Return is an object with all the information of the Star Wars characters. So far so good. But within this object, I have some sub-levels that are arrays and that besides some information, also has another URL that I need to consult to be able to print on the screen. The problem is that I'm not sure how to do this other query. To simplify, follow the return image:

Thisistheserviceget:

getData(page?:string):Observable<any[]>{if(page){this.URL=page;}returnthis.http.get(this.URL).map((response:Response)=><any[]>response.json()).catch(this.handleError);}

IknowthereisawaytodowithflatMapandforkJoin.Ieventried,butIdidnotgettheexpectedresult.

Followthislink: rxjs-observable

But I still could not.

    
asked by anonymous 06.05.2018 / 17:25

2 answers

0

Take a look, my solution would be to use a function that would help you and for a list of urls returns the observables of your requests. Then for each element that has this array of urls I call the function. Then you just have to map in order that you called. I am using the pipe operator depending on the version of rxjs that you are using it is not available there and just do .mergeMap and so on.

Keep in mind that with forkJoin if a request fails all fail.

import { mergeMap } from 'rxjs/operators/mergeMap';
import { map} from 'rxjs/operators/map';
import { of } from 'rxjs/observable/of';
import { forkJoin } from 'rxjs/observable/forkJoin';

getItems(urls: string[]): Observable<any> {
    return <Observable<Post>> forkJoin(
        urls.map(url=> <Observable<Post>> this.httpClient.get(url))
     ).pipe(concatAll());
}

getData(page?: string): Observable<any[]> {
        if(page){
          this.URL = page;
        }
        return this.http.get(this.URL).pipe(
        mergeMap((person: any) => {
         return forkJoin(
            of(person),
            this.getItems(person.films)
            this.getItems(person.species)
      ),
       map((data: any[]) => {
          let person= data[0];
          let films= data[1];
          let species= data[2];
          person.films= films;
          book.species= species;
          return person;
        })
    }))        
} 
    
07.05.2018 / 10:43
0

I do not see problem using 2 GET methods, for example:

And I think I should create 2 interfaces one for each return ... so I could get the easy result:

interface Retono1{

  retorno: number;
  retorno1: string;
  retorno2: string;
  retorno3: string[];
  retorno4: number;

}

retorno:Retorno1;

 this.http.get(this.url)
      .subscribe(result => {
          this.retorno = result.json();
          //primeiro retorno
           this.http.get(this.url)
           .subscribe(result => {

                 //segundo retorno

            })

 });

And I would use logic to get the second return for an interface too ...

    
06.09.2018 / 16:04