问题
I am new in using Observables. So here is my code
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
}
My problem is when i print the recipeList inside the subscribe i am getting the recipes but when i am printing outside its displaying undefined. How to save data to recipeList so that i can access it in my other methods.
回答1:
The problem with your code is that getRecipesFromUrl is an asynchronous operation. By the time it finishes, the log operation would have been executed, hence recipesList would be undefined. You should always subscribe and wait till the data arrives
You can do this
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);
}
}
}
来源:https://stackoverflow.com/questions/46860230/unable-to-subscribed-data-into-a-variable