0

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.

ark
  • 3,707
  • 5
  • 21
  • 36
  • 1
    The console.log outside of the subscribe doesn't have access to the data since fetching the data is asynchronous. Any method that needs access to recipeList has to be called after the data has loaded. – LLai Oct 21 '17 at 05:29
  • As in the duplicate, you need to do what you need/want inside the callback (subscribe) :) – AT82 Oct 21 '17 at 06:24

1 Answers1

0

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);
    }
 }
}
kidustiliksew
  • 443
  • 3
  • 11