简体   繁体   English

可见在Angular 2中不显示数据

[英]Observable not displaying data in Angular 2

I need to make a RESTful call and watch for changes using Angular 2 (the values should be updated every time it changes in the API). 我需要进行RESTful调用,并使用Angular 2监视更改(每次更改API中的值都应更新)。

In my service, I've added an Observable to get the data from the API: 在我的服务中,我添加了一个Observable来从API获取数据:

getData(): Observable<any[]> {
  return this.http.get(url)
    .map(res => res.json());
}

I call that in my constructor to update list: any = []; 我在constructor调用它来更新list: any = []; :

constructor(http: Http) {
  this.list = this.getData();
}

Then, in my HTML, I'm trying to display that data using ngFor : 然后,在我的HTML中,我尝试使用ngFor显示该数据:

<div *ngFor="let item of list | async">
  <h1>{{item.value}}</h1>
</div>

However, any data is being displayed. 但是,正在显示任何数据。 If I try to console.log(res) in map , I also don't get anything. 如果我尝试在map console.log(res) ,我也什么也得不到。 Any ideas of what I'm doing wrong here? 对我在这里做错的任何想法吗?

EDIT: After following Ivaro's suggestion, I'm getting an error with the AsyncPipe . 编辑:遵循Ivaro的建议后,我收到AsyncPipe错误。 However, if I remove it, how can I get the data to be updated when the API changes? 但是,如果删除它,如何在API更改时获取要更新的数据? I was using Observal.interval before, but I didn't want to call the API at a defined interval. 我以前使用过Observal.interval ,但是我不想以定义的时间间隔调用API。 I wanted it to watch for changes and update accordingly. 我希望它监视更改并相应地进行更新。

Here's my data structure, btw: 这是我的数据结构,顺便说一句:

[{
  "name": "apple",
  "value" 2
}, {
  "name": "banana",
  "value" 10
}]

An observable must be subscribed. 观察者必须订阅。 Since it is asynchronous, it returns undefined, and that is what is being assigned to this.list in your code. 由于它是异步的,因此它返回undefined,这就是在代码中分配给this.list的内容。 Instead subscribe: 而是订阅:

constructor(http: Http) {
  this.getData().subscribe(
        res => this.list = res,
        err = > console.log(err) /*handle error*/
    );
}

Edit: 编辑:

For the | async 对于| async | async pipe to work, use (list | async) (this doesn't need any subscription from observable as the async pipe internally subscribes) | async管道正常工作,使用(list | async) (由于async管道在内部进行订阅,因此不需要可观察到的任何订阅)

<div *ngFor="let item of (list | async)">
  <h1>{{item.value}}</h1>
</div>

The parentheses are required since execution happens from left to right and let item of list will be executed, which doesn't have required data. 括号是必需的,因为执行是从左到右执行的,将执行let item of list ,其中没有必需的数据。 So, ( list | async ) makes it have proper value in list . 因此, ( list | async )使它在list具有适当的值。

您正在寻找的解决方案通常称为Observable Data Services

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

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