简体   繁体   English

如何枚举Angular 2中从Observable Subscription返回的数据?

[英]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. 我具有有关可观察性工作原理的基本思想,我可以通过调用subscription方法并在模板中呈现数据来获取数据。 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: 我在组件中的ngInit方法:

 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. 您需要在subscribe方法中编写逻辑。 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. 您仍然可以在标记中使用userJson -Angular将检测this.userJson的值this.userJson更新,并将自动更新UI。

You need to call the console.log inside the subscribe to make it work, why do you need to call inside? 您需要在订阅中调用console.log使其起作用,为什么还要在内部调用? 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++) {
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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