简体   繁体   中英

How to enumerate data returned from Observable Subscription in Angular 2?

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?

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.

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++) {
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM