I have an array contains IDs and I want to subscribe to an observable for each ID in the array in an orderly manner (make a request for id 1 then 2 ...). I've tried foreach loop but the responses were unordered. and tried to create a for loop and increase the index from the subscriber but the browser crushed(because tons of requests have been sent before the index changed)
my code:
const uniqueGroups=[1,2,3,4,5,6];
uniqueGroups.forEach(groupId => {
this.magB1BaseService.getAttributeGroup(groupId)
.subscribe(data => {
this.AttributeGroups.push(data);
this.AttributeGroupsCollapses[data.ID] = false;
});
});
CodePudding user response:
One way to implement this is like below:
const uniqueGroups = of(1, 2, 3, 4, 5, 6);
uniqueGroups.pipe(concatMap(groupId => (
this.magB1BaseService.getAttributeGroup(groupId))
.subscribe(data => {
this.AttributeGroups.push(data);
this.AttributeGroupsCollapses[data.ID] = false;
})));
CodePudding user response:
Use concat operator to subscribe one by one.
const uniqueGroups = [1,2,3,4,5,6];
let obs: Array<Observable<any>> = [];
uniqueGroups.forEach( groupId => {
obs.push(this.magB1BaseService.getAttributeGroup(groupId));
});
concat(...obs).subscribe( data => {
this.AttributeGroups.push(data);
this.AttributeGroupsCollapses[data.ID] = false;
});