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.
这是我的错误。我一直在寻找解决方法,但没有什么好运气。我对Angular或TypeScript的经验非常有限。实际上我正在跟随一个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[] 从最开始就没有被加载。
感谢任何帮助。