I am grappling with the concept of Observables in RxJs. My task involves displaying all users for a specific site on a page. The User and SiteUser entities are located in separate API endpoints. Here are the relevant endpoints:
userService.getSiteUsers(siteId: string): Observable<SiteUser[]>;
where
export class SiteUser {
site_id: string;
user_id: string;
}
and
userService.getUser(user_id: string): Observable<User>;
where
export class User {
id: string;
name: string;
email: string;
....
}
To accomplish this, I need to:
- Retrieve all user ids for a specific site using the siteUsers API
- For each user id, fetch user details using the getUser API call
This can be done as follows:
let users: User[] = []; // bound in html view to display table
this.userService.getSiteUsers("my site id")
.subscribe((siteUsers) => {
for (let siteUser of siteUsers) {
this.userService.getUser(siteUser.user_id)
.subscribe((user) => {
users.push(user);
});
}
});
However, I feel that this approach is not optimal. There must be a better way to handle it using Observables. While I am new to Observables, my understanding suggests that there should be a cleaner approach. I tried the following idea but couldn't get it to work:
A potential solution could involve:
this.userService.getSiteUsers("my site id")
.selectMany((siteUser) => this.userService.getUser(user))
.mergeAll()
.subscribe((users) => {
this.users = users;
});
If anyone has suggestions or tips on how to improve this code, please share as I am struggling to implement it.
EDIT------
Possibly something along these lines:
this.userService.getSiteUsers("my site id")
.switchMap(
(siteUsers) => {
let userQueries: Observable<User>[] = [];
for (let siteUser of siteUsers) {
userQueries.push(this.userService.getUser(siteUser.user_id));
}
return Observable.forkJoin(userQueries);
}
)
.subscribe((users) => {
this.users = users;
});