无法将数据订阅到变量中

时间:2017-10-21 05:02:51

标签: angular angular-observable

我是使用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,以便我可以使用其他方法访问它。

1 个答案:

答案 0 :(得分: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);
    }
 }
}