Angular 确保多次订阅会产生预期的行为

Angular 确保多次订阅会产生预期的行为,angular,typescript,loops,observable,Angular,Typescript,Loops,Observable,我正在开发配方推荐API的前端。给定一个用户ID,我可以订阅一个getRec()函数并检索一个建议列表(recipeid、ingredientid),我要为其执行以下操作: 订阅getRecipe()函数并将recipeid转换为配方信息 IFoodItem: export interface IFoodItem { id: number; name: string; value: number; } 尝试更改行this.recipes.push(recipe)到此。配方[i]

我正在开发配方推荐API的前端。给定一个用户ID,我可以订阅一个getRec()函数并检索一个建议列表(recipeid、ingredientid),我要为其执行以下操作:

  • 订阅getRecipe()函数并将recipeid转换为配方信息
IFoodItem:

export interface IFoodItem {
  id: number;
  name: string;
  value: number;
}

尝试更改行
this.recipes.push(recipe)
此。配方[i]=配方推荐
功能中选择code>。

嗯?!真不敢相信是这样。你介意详细说明一下
这个.recipes.push(recipe)之间的区别吗
这个。配方[i]=配方?非常感谢。我是否也应该对
这个.recipes[recipe\u index].items[j].push(cart\u item)做类似的更改?调用
getRecipe
回调的顺序与调用它的顺序不同。因此,例如,如果您得到了三个建议,并为每个建议调用
getRecipe
,那么第二个建议可能会在第一个建议之前返回。在这种情况下,在您的原始代码中,第二个配方将是
this.recipes
数组中的第一个配方。
this.recipes[recipe\u index].items[j].push(cart\u item)
仅当购物车项目的顺序与您有关时才需要更改。
  private addRecommendedItems(recipe_index, recipe_ingredientsids) {
    this.recipes[recipe_index].items = [];

    for (let j = 0; j < recipe_ingredientsids.length; j++) {
      this.recipes[recipe_index].items[j] = [];

      this.listService
        .getRecommendedItems(recipe_ingredientsids[j])
        .subscribe((cart_items_ids) => {
          for (let k = 0; k < cart_items_ids.length; k++) {
            this.listService
              .getItem(cart_items_ids[k])
              .subscribe((cart_item) => {
                this.recipes[recipe_index].items[j].push(cart_item);
              });
          }
        });
    }
  }
export interface IRecipe {
  id?: number;
  title?: string;
  instructions?: string;
  items?: IFoodItem[][];
}
export interface IFoodItem {
  id: number;
  name: string;
  value: number;
}