Advertisement
Guest User

Untitled

a guest
Apr 7th, 2020
186
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. interface Planet {
  2.   name: string;
  3. }
  4.  
  5. interface PlanetResult {
  6.   count: number;
  7.   next: string;
  8.   results: Planet[];
  9. }
  10.  
  11. @Injectable({
  12.   providedIn: 'root'
  13. })
  14. export class PlanetService {
  15.   constructor(private httpClient: HttpClient) {}
  16.  
  17.   getAllPlanets(): Observable<Planet[]> {
  18.     return this.fetchPlanets().pipe(
  19.       expand(result =>
  20.         iif(() => !!result.next,
  21.           this.fetchPlanets(result.next),
  22.           EMPTY
  23.         )
  24.       ),
  25.       pluck('results'),
  26.       reduce((acc, planets) => acc.concat(planets), []),
  27.     );
  28.   }
  29.  
  30.   private fetchPlanets(nextUrl?: string): Observable<PlanetResult> {
  31.     const startUrl = 'https://swapi.co/api/planets/';
  32.     return this.httpClient.get<PlanetResult>(nextUrl || startUrl);
  33.   }
  34. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement