【发布时间】:2019-11-18 00:48:20
【问题描述】:
我有一个包含用户表的 Angular 组件,它们显示正确,但打开浏览器控制台时出现错误:
compiler.js:18239 ERROR TypeError: Cannot read property 'length' of undefined
compiler.js:18239 ERROR CONTEXT DebugContext_ {view: {…}, nodeIndex: 2, nodeDef: {…}, elDef: {…}, elView: {…}}
我已将用户加载移至 ngOnInit,在那里我订阅并将数据保存在 'this.users' 数组中,
users: User[] = [];
constructor(
public userService: UserService
) { }
ngOnInit(): void {
this.userService.getAllUsers()
.subscribe(
data => {
this.users = data;
}
);
}
HTML 组件:
<nz-table [nzData]="users" [nzShowPagination]="false">
<tr>
<th>User</th>
</tr>
<tbody>
<tr *ngFor="let data of users">
<td>{{ data.userName }}</td>
</tr>
</tbody>
</nz-table>
为什么在列表中明确定义并显示数据时出现未定义错误?
【问题讨论】:
-
如何在组件中初始化你的
users数组? -
尝试添加
<nz-table *ngIf="users" ....> -
定义
users数组时尝试设置默认值[] -
这是因为你的用户对象在组件初始化时是未定义的,当数据存在时你给它分配数据。要解决此问题,请将用户定义为空数组。用户 = [];
-
你有没有在函数内部写代码?
标签: angular typescript