【发布时间】:2018-05-15 18:10:31
【问题描述】:
我有 2 个组件,一个从外部服务获取数据,另一个显示它。
第一个组件的构造函数:
constructor( private deviceInfoApi: DeviceInfoApiService ) {
this.devicesPromise = this.deviceInfoApi.getDevices(false, false, false);
let tempDevicesPromise = this.deviceInfoApi.getDevices(false, true, false).then(
result => {
this.devicesPromise = tempDevicesPromise;
}
);
}
及其模板:
<app-devices-table [devices]="devicesPromise | async"></app-devices-table>
这是我的工作:
- 我使用 getDevices(false,false,false) 获取一些数据 - 这个数据带来的信息比我需要的要少,但速度更快,并且足以显示某些内容
- 我使用 getDevices(false,true,false) 获取一些数据 - 由于第二个参数为 true,它会为我提供更多信息,但获得响应需要更长的时间。
所以我想先显示一些基本信息,当我收到更详细的包时,我会替换它。
第二个组件的输入:
@Input() devices: Array<any>;
及其模板:
<table class="ui inverted table loading">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Type</th>
<th>Online</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let device of devices">
<td>{{ device.Id }}</td>
<td>{{ device.Name }}</td>
<td>{{ device.DeviceType }}</td>
<td>{{ device.IsConnected }}</td>
</tr>
</tbody>
</table>
结果是第一次调用 getDevices 会返回一些结果并正确显示。一旦第二个结果到达并且我的 devicesPromise 被替换,它就会中断 - 不显示任何表格。
我将 ngOnChanges() 添加到我的第二个组件(带有表格的那个):
ngOnChanges() {
console.log('CHANGES');
console.log(this.devices);
}
我看到第一个 getDevices() 结果运行良好 - console.log 显示我的设备。第二个显示“未定义”。
为什么会这样?不能用异步管道更新输入吗? 我确信对 getDevices() 的第二次调用会返回正确的数据,因为我在第一个组件的代码中进行了 console.logged 并且很好。只有第二个组件将其视为未定义。
【问题讨论】:
标签: javascript html angular