【问题标题】:Angular 4 - Subscribe gets called mutiple times inside for/switch loopAngular 4 - 在 for/switch 循环中多次调用订阅
【发布时间】:2018-04-06 12:47:53
【问题描述】:

我有一个字符串数组,看起来像这样(每次都是随机的)

["consumables", "spells", "spells", "consumables", "spells", "consumables", "spells", "characters", "characters", "consumables"]

然后我循环遍历这个数组,根据索引我调用不同的.subscribe 并将一些数据推送到新数组。

for (var i = 0; i < arrayOfItems.length; i++) {  
    switch (arrayOfItems[i]) {
        case 'spells':
            this.spellsSubscribeSet = true;
            this.spellsSubscribe = this.spells.subscribe(data => {
                const itemId = this.getRandom(data.length - 1);
                this.rewardPack.push(data[itemId]);
            });
            break;
        case 'characters':
            this.charactersSubscribeSet = true;
            this.charactersSubscribe = this.characters.subscribe(data => {
                const itemId = this.getRandom(data.length - 1);
                this.rewardPack.push(data[itemId]);
            });
            break;
        case 'consumables':
            this.consumablesSubscribeSet = true;
            this.consumablesSubscribe = this.consumables.subscribe(data => {
                const itemId = this.getRandom(data.length - 1);
                this.rewardPack.push(data[itemId]);
            });
            break;
        default:
            return null;
    }
}

.getRandom 是一个返回随机数的普通函数。

getRandom(x) {
    return Math.floor(Math.random() * x);
}

只有“法术”才会被多次调用的奇怪东西。

我读过一些关于 .flatMap 的内容,但我认为这对我没有帮助,因为我正在循环一个普通数组。

我正在使用 Firestore 数据库

【问题讨论】:

  • 为什么要订阅多次?每当有事情发生时,订阅的目的不是要通知吗?因此,您应该简单地为每个事件订阅一次,工作就完成了。忘记switch里面的for
  • 或者至少不要重复你自己。 this[arrayOfItems[i]].subscribe 将涵盖您的所有案例,如果您有 50 个不同的项目,而不是重复您的代码 50 次。
  • @JeremyThille 您的 cmets 让我想到了可以实现此功能的其他方法。所以现在我在构造函数加载时将我需要的这 3 个集合保存在变量中。然后当我稍后在代码中调用它时,它可以完美运行。

标签: javascript arrays angular typescript google-cloud-firestore


【解决方案1】:

我在构造函数加载时保存了我需要的所有数据,然后在代码中需要它的地方使用它。

【讨论】:

    【解决方案2】:

    您的循环可能多次遇到“spells”案例,该案例多次订阅了 spells 事件,因此订阅中的代码被多次调用。

    在每种情况下,您都应该检查您是否已经订阅了该事件。像这样的:

         if (!this.consumablesSubscribeSet){
            this.consumablesSubscribeSet = true;
            this.consumablesSubscribe = this.consumables.subscribe(data => {
            const itemId = this.getRandom(data.length - 1);
            this.rewardPack.push(data[itemId]);
            });
         }
         break;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-01
      • 2018-02-02
      • 2019-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多