I have Vanilla.js (TypeScript) HTTP client that returned Promises, like so:
class Person {
name: string;
id: number;
friendsIds: number[];
}
class MyClient {
getPersonInfo(personId: number): Promise<Person> {
return fetch( '/people/' + personId)
.then( r => r.json() as Person );
}
}
My display code gets the details of each Person's friends, like so:
refresh(): void {
client.getPersonInfo( 123 )
.then( (person: Person) => {
// array-of-promises:
let friendsDetailsPromises: Promise<Person>[] = person.friendsIds.map( friendId => client.getPersonInfo( friendId ) );
// promise-of-array:
let friendsDetailsAll : Promise<Person[]> = Promise.all( friendsDetailsPromises );
return friendsDetailsAll;
} )
.then( (friendsDetails: Person[]) => {
// (do stuff for each Person)
} )
.catch( reason => console.error( reason ) );
}
I'm trying to move this over to Angular 2's built-in HTTP client which returns Observable<T>
instead of Promise<T>
, so far I have:
class MyClient {
private http: HttpClient;
getPersonInfo(personId: number): Observable<Person> {
return this.http.get<Person>( '/person/' + personId );
}
}
refresh(): void {
client.getPersonInfo( 123 )
.flatMap( (person: Person) => {
// ...now what?
} )
.subscribe(
(friendsDetails: Person[]) => {
// (do stuff for each Person)
},
err => console.error( err )
)
);
}
I'm stuck on what I'm supposed to do inside of flatMap
.
I saw this QA which asks about converting Promise.all
to Observable
( Promise.all behavior with RxJS Observables? ) and the answer is to use forkJoin
but also suggests flatMap
and linking to this posting ( RxJS Promise Composition (passing data) ) but this problem doesn't resemble mine at all.