In my Typescript code for Angular 11, I am working with two observables. The first one, getSelfPurchases(), returns data objects containing information like id, user_id, script_id, and pp_id. On the other hand, the second observable, getScriptDetails(32), provides details such as the script's name, author, and price.
My current implementation involves looping through the results of the first observable, making a call to the second observable for each item, and appending the retrieved script name to the original object. While this approach works, I believe it may not be the most efficient or elegant solution.
I have been exploring RXJS functionalities like switch map to optimize my code. However, I'm uncertain if using switch map would improve the performance significantly or if there are better alternatives. I would appreciate any insights or suggestions on how to refine this process.
this.userService.getSelfPurchases().subscribe(response => { // first observable
this.purchases = response;
this.purchases.forEach((purchase, index) => { // loop through our results
this.scriptService.getScriptDetails(purchase.script_id).subscribe(responseTwo => { // second observable
if (responseTwo[0] && responseTwo[0].sname !== undefined) {
this.purchases[index].sname = responseTwo[0].sname; // append to our original purchases object
}
});
});
});