1

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;
        });
    });
1
  • 1
    try concatMap instead of forEach Commented Dec 23, 2021 at 9:25

2 Answers 2

2

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;
      })));
Sign up to request clarification or add additional context in comments.

2 Comments

what if I don't know the array values? how can I make it like uniqueGroups in your code?
You can also use Observable.of(uniqueGroups);
1

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;
});

2 Comments

Please don't post only code as an answer, but also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes.
@WangJie your answer has one error let obs Observable<any>=[] should be let obs Observable<any>=[] , and it works as well, thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.