无法将数据订阅到变量中
问题描述:
我是使用Observable的新手。因此,这里是我的代码无法将数据订阅到变量中
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,以便我可以通过其他方法访问它。
答
你的代码的问题是,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);
}
}
}
的执行console.log的认购没有因为获取数据对数据的访问是异步的外面。任何需要访问recipeList的方法都必须在数据加载后调用。 – LLai
在复制中,您需要在回调(订阅)中执行您需要/想要的内容:) – Alex