TypeScript是讲究数据类型的,基本可以说面向对象开发的思路。今天准备在系统里增加实体类。
以device这个组件为例,增加Device实体类。
1. 添加device.ts
在device目录下添加device.ts, 根据服务器端的数据库模型,该类的内容为:
export interface Device {
id: number;
no: string;
name: string;
deployTime: string;
}
2. 在组件中引用和使用
device.component.ts, 从服务端获取device列表。
...
import { Device } from './device';
...
devices:Device[] = new Array;
...
getDevice() {
this.deviceService.getDevice().subscribe(
(data:Device[])=>{ this.devices = data; } //类型自动隐式转换
);
}
3. 在页面上展示device列表
device.component.html
<table style="background-color:lightblue;">
<tr *ngFor="let device of devices">
<td>{{device.no}}</td>
<td>{{device.name}}</td>
<td>{{device.deployTime}}</td>
</tr>
</table>
效果: