[英]Iterating over Observable that contains an Array with *ngFor in Angular
I have a device that contains several items.我有一个包含多个项目的设备。 Now I want to display all items of the device in my Angular App on the HTML page, but I have problems iterating the observable that contains the array.
现在,我想在 HTML 页面上的 Angular App 中显示设备的所有项目,但是在迭代包含数组的 observable 时遇到问题。 I get the following error with my current code.
我当前的代码出现以下错误。
Error: Cannot find a differ supporting object '[object Object]' of type 'object'.
错误:找不到类型为“object”的不同支持对象“[object Object]”。 NgFor only supports binding to Iterables such as Arrays.
NgFor 仅支持绑定到可迭代对象,例如数组。
<tbody *ngFor="let item of (device | async).itemMap">
<tr>
<td>{{ item.name }}</td>
// ...
</tr>
</tbody>
export interface Device {
items: DeviceItem[];
}
@Input()
public device: Observable<Device>;
If your observable emits a Device
model as you described (and NOT an array of Device
) :如果您的 observable 按照您的描述发出
Device
模型(而不是Device
数组):
export interface Device {
items: DeviceItem[];
}
public device$: Observable<Device>;
In the code above, I recommend you to use the convention device$
(a $
symbol as a suffix to differenciate Observable
and regular type).在上面的代码中,我建议你使用约定
device$
(一个$
符号作为区分Observable
和常规类型的后缀)。
your template code should be :您的模板代码应该是:
<tr *ngFor="let item of (device$ | async).items">
<td>{{ item.name }}</td>
// ...
</tr>
or或者
<ng-container *ngIf="device$ | async as device">
<table>
<tr *ngFor="let item of device.items">
<td>{{ item.name }}</td>
...
</tr>
</table>
</ng-container>
Well *ngFor
iterates only over a collection.So what you have to do to create a subject
which contains your device type array and fill the data over it.那么
*ngFor
只迭代一个集合。那么你必须做什么来创建一个包含你的设备类型数组的subject
并在它上面填充数据。
public device : Subject<Device[]> = new Subject();
and then fill this device with data like this -然后用这样的数据填充这个设备 -
this.device.next(data);
Map device to items
in ts file (you will need to update it manually if input is changed):将设备映射到 ts 文件中的
items
(如果输入更改,您将需要手动更新它):
export interface Device {
items: DeviceItem[];
}
@Input()
public device: Observable<Device>;
public items$ = device.pipe(map(x => x.items));
And then use it as normal:然后照常使用它:
<tr *ngFor="let item of items$">
<td>{{ item.name }}</td>
// ...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.