Created
July 11, 2024 17:53
-
-
Save mugan86/db65e66404d89b89b82a292d2257dab9 to your computer and use it in GitHub Desktop.
ForkJoin
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { HttpClient } from '@angular/common/http'; | |
import { Injectable } from '@angular/core'; | |
import { Observable, map, of, switchMap } from 'rxjs'; | |
import { forkJoin } from 'rxjs/internal/observable/forkJoin'; | |
@Injectable({ | |
providedIn: 'root', | |
}) | |
export class AppService { | |
constructor(private http: HttpClient) {} | |
getSwapiComplete(): Observable<any> { | |
const character = this.http.get('https://swapi.dev/api/people/2'); | |
const characterHomeworld = this.http.get('https://swapi.dev/api/planets/2'); | |
const characterSpecies = this.http.get('https://swapi.dev/api/species/2/'); | |
return forkJoin({ | |
main: character, | |
planets: characterHomeworld, | |
species: characterSpecies, | |
}) | |
.pipe( | |
map(({ main, planets, species }) => { | |
return { | |
...main, | |
homeworld: planets, | |
species: species, | |
// films: switchMap(()) | |
}; | |
}) | |
) | |
.pipe( | |
switchMap((value) => { | |
return forkJoin([ | |
of(value), | |
...value['films'].map((value) => this.http.get(value)), | |
]); | |
}) | |
) | |
.pipe( | |
map((data) => { | |
return { | |
...data[0], | |
films: data.slice(1), | |
}; | |
}) | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment