Skip to content

Instantly share code, notes, and snippets.

@mugan86
Created July 11, 2024 17:53
Show Gist options
  • Save mugan86/db65e66404d89b89b82a292d2257dab9 to your computer and use it in GitHub Desktop.
Save mugan86/db65e66404d89b89b82a292d2257dab9 to your computer and use it in GitHub Desktop.
ForkJoin
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