【问题标题】:All objects ID's are the same when pushing new elements to an array将新元素推送到数组时,所有对象 ID 都相同
【发布时间】:2022-01-11 01:39:14
【问题描述】:

我正在执行以下代码:

        dietDay.meals.forEach((meal) => {
          meal.mealProducts.forEach((mealProduct) => {
            if (
              mealProduct.product.id &&
              this.fetchedProductIds.includes(mealProduct.product.id)
            ) {
              return;
            } else if (mealProduct.product.id) {
              this.fetchedProductIds.push(mealProduct.product.id);
              this.httpClient.get(environment.backendUrl + '/products/' + mealProduct.product.id)
              .subscribe((response: any) => {
                this.products.push(response);
                this.setDaySummary();
                this.setActiveMealSummary();
              });
            }
          });
        });
      });

循环遍历餐食,并使用 GET 调用从后端获取产品数据。

this.products 数组包含一个 Products 类型的对象数组。 在每次迭代中,都会从后端下载一个新产品并将其推送到数组中。 循环运行后,数组中的所有产品 ID 都相同,但所有其他属性都不同。

正如您在 this.products 数组的控制台日志输出中看到的,两个对象具有相同的 ID,即使当我在 console.log 输出来自后端的每个单独响应时,ID 也是不同的。

发生了什么事?

【问题讨论】:

  • 看起来您正在从代码中的某处更改数据。您是否尝试在 this.products.push(response) 语句之后记录 this.products
  • 是的,即使推入this.products的对象具有不同的id,它也包含相同的id

标签: javascript angular typescript rxjs


【解决方案1】:

this.setDaySummary() 函数中,我使用 '=' 而不是 '===' 并且它正在分配产品 ID。

【讨论】:

    猜你喜欢
    • 2021-12-25
    • 2012-05-11
    • 1970-01-01
    • 2023-01-28
    • 1970-01-01
    • 2014-04-26
    • 2017-12-14
    相关资源
    最近更新 更多