Unable to subscribed data into a variable [duplicate]

耗尽温柔 提交于 2019-12-11 17:42:55

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!