【问题标题】:How to enumerate data returned from Observable Subscription in Angular 2?如何在 Angular 2 中枚举从 Observable Subscription 返回的数据?
【发布时间】:2019-01-13 09:45:55
【问题描述】:

我对 observable 的工作原理有了基本的了解,我可以通过调用 subscribe 方法获取数据并在我的模板中呈现数据。但我无法枚举组件中可观察对象返回的数据。我想在将数据发送到我的模板之前在组件级别处理我的数据。

到目前为止我已经尝试过了:

我的服务:

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

我在组件中的 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++) {
    }
}

不确定如何处理?

【问题讨论】:

    标签: angular observable angular2-services angularjs-components


    【解决方案1】:

    您需要在 subscribe 方法中编写您的逻辑。是异步调用,不知道什么时候结束。

    this.countryService.getCountries().subscribe((users => {
       this.userJson = users;
    
       console.log(this.userJson);
    
       for (var i = 0; i < this.userJson.length; i++) {
    
       }
    }));
    

    您仍然可以在标记中使用 userJson - Angular 会检测到 this.userJson 的值何时更新,并自动更新 UI。

    【讨论】:

    • 谢谢!好快啊……! :)
    【解决方案2】:

    你需要在订阅里面调用console.log才能让它工作,为什么你需要在里面调用呢?因为它是一个异步请求;您可以通过如下调用函数来循环项目,

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

    【讨论】:

      猜你喜欢
      • 2016-10-18
      • 2017-06-24
      • 1970-01-01
      • 2018-07-14
      • 2014-03-28
      • 2017-10-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多