0

我是使用 Observables 的新手。所以这是我的代码

recipesList:Recipe[];


 private recipes;
 constructor(private shoppingService:ShoppingListService,private http:Http){
   this.getRecipesFromUrl().subscribe((data)=>{
     this.recipesList=data;
     console.log(this.recipesList);//printing array containing recipes
   });
   console.log(this.recipesList);//printing undefined
}

我的问题是,当我在订阅中打印 recipeList 时,我得到了食谱,但是当我在其显示未定义之外打印时。如何将数据保存到 recipeList 以便我可以在其他方法中访问它。

4

1 回答 1

0

您的代码的问题是 getRecipesFromUrl 是一个异步操作。到它完成时,日志操作将被执行,因此 recipesList 将是未定义的。您应该始终订阅并等待数据到达

你可以这样做

 recipesList: Observable<Array<Recipe>>;

 constructor(private shoppingService:ShoppingListService, private http:Http) {
    this.recipesList = this.getRecipesFromUrl();

    //Subscribe and handle data when it arrives
    this.recipesList.subscribe((recipes) => {
        console.log("Recipes", recipes);
    }
 }

 list() {
    //Subscribe here too
    this.recipesList.subscribe((recipes) => {
        console.log("Recipes", recipes);
    }
 }
}
于 2017-10-21T06:53:48.887 回答