简体   繁体   English

如何从数组中异步订阅 observable - angular

[英]how to subscribe an observable asynchronously from an array - angular

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...).我有一个包含 ID 的数组,我想以有序的方式订阅数组中每个 ID 的 observable(请求 id 1 然后 2 ...)。 I've tried foreach loop but the responses were unordered.我试过 foreach 循环,但响应是无序的。 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)并尝试创建一个 for 循环并增加订阅者的索引,但浏览器崩溃了(因为在索引更改之前已经发送了大量请求)

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

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

Use concat operator to subscribe one by one.使用 concat 操作符一一订阅。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM