-1

I've the basic idea about how observable works, I'm able to get the data by calling subscribe method and render the data in my template. But I could not enumerate the data returned by the observable in my component. I would like to process my data at component level before sending them to my template.

I've tried this so far:

My Service:

getCountries(): Observable<IUser> {
   return this.http.get<IUser>('https://jsonplaceholder.typicode.com/posts');
}

My ngInit method in the component:

 ngOnInit() {
    this.countryService.getCountries().subscribe((users => {
       this.userJson = users;
    }));

    console.log(this.userJson); // Showing undefined

    //giving exception while calling length property
    for (var i = 0; i < this.userJson.length; i++) {
    }
}

Not sure how to approach this?

Jai
  • 74,255
  • 12
  • 74
  • 103
Badhon Jain
  • 938
  • 6
  • 20
  • 38

2 Answers2

1

You need to write your logic inside subscribe method. It is an asynchronous call and you can't know when it will be finished.

this.countryService.getCountries().subscribe((users => {
   this.userJson = users;

   console.log(this.userJson);

   for (var i = 0; i < this.userJson.length; i++) {

   }
}));

You can still work with userJson in the markup - Angular will detect when the value of the this.userJson will be updated and it will update UI automatically.

Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112
1

You need to call the console.log inside the subscribe to make it work, why do you need to call inside? because its an asynchronous request;You can loop over the items by calling a function as follows,

ngOnInit() {
  this.countryService.getCountries().subscribe((users => {
    this.userJson = users;
    console.log(this.userJson); 
    printMe(this.usersJson);
}));

printMe : void (){
  for (var i = 0; i < this.userJson.length; i++) {
  }
}
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396