无法将数据订阅到变量中 [英] Unable to subscribed data into a variable

查看:48
本文介绍了无法将数据订阅到变量中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是使用Observables的新手.这是我的代码

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.

推荐答案

您的代码存在的问题是getRecipesFromUrl是异步操作.到完成时,日志操作将已经执行,因此配方清单将是未定义的.您应该始终订阅并等待数据到达

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

您可以做到

 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);
    }
 }
}

这篇关于无法将数据订阅到变量中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆