【发布时间】:2022-01-15 22:37:34
【问题描述】:
Compiled with problems:X
ERROR
src/app/components/users/users.component.html:2:22 - error TS2532: Object is possibly 'undefined'.
2 <ul *ngIf="loaded && users?.length > 0">
~~~~~~~~~~~~~~~~~
src/app/components/users/users.component.ts:6:16
6 templateUrl: './users.component.html',
~~~~~~~~~~~~~~~~~~~~~~~~
Error occurs in the template of component UsersComponent.
这是我的错误。我一直在四处寻找,但运气不佳。我对角度或打字稿的经验非常有限。我实际上正在学习udemy课程。这是我第一次遇到“可选链接”,所以我可能会忽略一些明显的东西。
产生问题的代码相当简单
<h2>Users</h2>
<ul *ngIf="loaded && users?.length > 0">
<li *ngFor="let user of users">
<h3>{{ user.firstName }} {{ user.lastName }}</h3>
<ul *ngIf="showExtended">
<li>age: {{ user.age }}</li>
<li>Address: {{ user.address.street }} {{ user.address.city }} {{ user.address.state }}</li>
</ul>
</li>
</ul>
component.ts 只是提供了一个 users[] 但粗略的试图解释某种加载动画。这就是为什么 users[] 有时没有从一开始就加载的原因。
感谢任何帮助。
【问题讨论】:
-
使用!而不是 ?
标签: angular typescript optional-chaining