My current challenge involves nesting subscriptions within "subscribe" due to the dependency of some data on the response of the previous subscription. This data flows down the subscription chain until it is stored in an array.
Starting with an array of IDs, I make a call to a service to convert those IDs to Objects. The code structure for this process looks like:
idArray.forEach(id =>
this.getObjByID(id)));
}
getOjByID(ID: number): void {
this._APIService.getObjByID(ID).subscribe(
obj => {
this.getDefaultConfig(obj);
});
}
After retrieving these Objects, I then proceed to obtain a configuration file for each Obj. The relevant code snippet is as follows:
getDefaultConfig(obj: any): void {
this._APIService.getDefaultConfig(obj.id).subscribe(
res => {
obj.config = res;
this.getPrices(obj);
});
}
Finally, the Object and its configuration are passed to a final subscription where a price object is added to the Object. Subsequently, the Object is pushed to an array of objects which are then rendered on the screen. The last piece of code for this process is outlined below:
getPrices(obj: any): void {
this._PriceService.getPrice(obj).subscribe(
res => {
obj.price = res;
this.objs.push(obj);
});
}
I am encountering a bug related to the behavior of the subscribe/observables concept in my implementation. While the intended outcome is for the chain of actions to be executed for each ID present in my idArray, there seems to be instances where certain subscriptions or functions are being duplicated. Although no errors are displayed in the console, the issue is noticeable by the count of items in the final array "objs".
In an attempt to resolve this issue, I experimented with adding ".first()" or ".take(1)" before ".subscribe" across all functions. This adjustment managed to eliminate duplicate obj objects in the objs array, however, they all shared the same "price" object.
I am seeking insights into what could potentially be incorrect with my utilization of observables leading to this unexpected behavior?