javascript - 无法读取未定义的 Javascript/Typescript 的属性“用户名”
问题描述
我试图创建一个 Profile 对象列表,然后在列表中显示每个对象的某些元素。我创建了一个名为 Profile 的公共接口,将其导入到我的组件中,然后我创建了一个 Profile 类型的新对象并赋值id, username, and profilepic
。
问题是,虽然我能够设置对象并将其分配给我的数组,但我的*ngFor
语句似乎没有看到 attributes 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)
解决方案
displayActiveUser = new Array<Profile>(10);
创建了一个包含 10 个未定义的数组。
您想要做的是使用地图功能将您的源转换为显示的数据。在现代 JavaScript 中,我们并没有真正接触到 for 循环,人们倾向于坚持使用 map 和 filter 之类的函数。
this.displayActiveUser = this.activeUserArray.map(user => transformUser(user));
其中 transformUser 是一个将一个对象映射到另一个对象的函数
推荐阅读
- spring-boot - spring 配置服务器无法通过 webhook 刷新
- highcharts - 条形图高度错误
- linkedin - Linkedin API - Picture-urls::original - 禁止 403 错误
- node.js - 为 NPM 注册表创建代理服务器
- docker - 如何通过命令行为 Docker for Mac 配置交换空间?
- javascript - ionic html5 选择/键盘打开,向上滚动视图和选项卡并在 iOS 上的选项卡后创建空白空间
- python - Python:将对象插入 .xlsx 文件
- r - 如何从本地文件夹安装 R 包,而依赖项安装仍在同一文件夹中?
- ios - 如何在 iOS 中为 React Native 应用程序禁用系统的粗体文本可访问性设置?
- python - 将 %m-%d 转换为 dayofyear 格式