【发布时间】:2020-08-26 23:26:30
【问题描述】:
我试图创建一个 Profile 对象列表,然后在列表中显示每个对象的某些元素。我创建了一个名为 Profile 的公共接口,将其导入到我的组件中,然后我创建了一个 Profile 类型的新对象并分配 id, username, and profilepic。
问题是,虽然我能够设置对象并将其分配给我的数组,但我的*ngFor 语句似乎没有看到属性id,username, or profilepic。我觉得这很奇怪,因为如果我打电话给console.log(curP.username);,我会在控制台中得到正确的用户名。我是否定义错误? console.log(this.displayActiverUser); 还返回正确的用户列表,id,username,profilepic。
界面:
export interface Profile {
id: any;
username: any;
profilePic: any;
}
组件:
displayActiveUser = new Array<Profile>(10); //this is the array displayed as users
activeUserArray = new Array(10);
for (var n = 0; n < numAvalAcct; n++){
let curP: Profile = {id: parseInt(this.activeUserArray[n][1]),username: this.activeUserArray[n][0], profilePic: "testurl"};
console.log("usernm", curP.username);
this.displayActiveUser[n] = curP;
}
HTML *ngFor(错误出现在{{profile.username}}所在的行
<div class="list-group">
<a *ngFor="let profile of displayActiveUser" (click)="followedNewUser(profile)" href="" target="popup" class="list-group-item list-group-item-action">
<img src="" class="rounded-circle" alt="profile picture" width="25" height="25"> {{profile.username}}
</a>
</div>
console.log(this.displayActiverUser); 的输出
0: {id: 135, username: "adamhaddad4", profilePic: "testurl"}
1: {id: 136, username: "ian.mccleary", profilePic: "testUrl"}
2: {id: 1, username: "dddd", profilePic: "testurl"}
3: {id: 134, username: "timtim1", profilePic: "testUrl"}
编辑:完整的错误是:
ERROR TypeError: Cannot read property 'username' of undefined
at FollowForFollowComponent_a_6_Template (follow-for-follow.component.html:8)
at executeTemplate (core.js:7329)
at refreshView (core.js:7198)
at refreshEmbeddedViews (core.js:8289)
at refreshView (core.js:7222)
at refreshComponent (core.js:8335)
at refreshChildComponents (core.js:6991)
at refreshView (core.js:7248)
at refreshEmbeddedViews (core.js:8289)
at refreshView (core.js:7222)
【问题讨论】:
-
你能分享你的错误信息吗? @Ian McCleary
-
@Muthupriya 错误类型错误:无法在刷新视图(核心。 js:7198) 在 refreshEmbeddedViews (core.js:8289) 在 refreshView (core.js:7222) 在 refreshComponent (core.js:8335) 在 refreshChildComponents (core.js:6991) 在 refreshView (core.js:7248) 在refreshEmbeddedViews (core.js:8289) 在 refreshView (core.js:7222)
-
如果不看更多代码就很难知道,但我敢打赌,在您将元素复制到
displayActiveUser数组之前,视图正在执行。您将其初始化为一个包含 10 个元素的数组,因此ngFor正在执行,但每个项目都是undefined,因为它们尚未被复制。 -
你创建了一个有 10 个空槽的数组,只填充了 4 个。
-
你是对的!我只是同时想通了....通过用 10 个元素初始化列表,我的视图已经在尝试在分配我的值之前显示列表。我通过使用
.push()而不是this.displayActiveUser[n] = curP;来修复它。如果您想将您的评论变成答案,请随意。谢谢!!
标签: javascript angular typescript