无法读取未定义的Javascript / Typescript的属性“用户名”

时间:2020-08-25 20:33:53

标签: javascript angular typescript

我试图创建一个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)

3 个答案:

答案 0 :(得分:1)

displayActiveUser = new Array<Profile>(10);创建了一个其中包含10个未定义数组。

您要做的是使用地图功能将源转换为显示的数据。在现代JavaScript中,我们并没有真正达到for循环,人们倾向于使用map和filter之类的功能。

this.displayActiveUser = this.activeUserArray.map(user => transformUser(user));

其中transformUser是一个将一个对象映射到另一个对象的函数

答案 1 :(得分:1)

displayActiveUser = new Array<Profile>(10);

初始化具有10个空插槽的数组。

请参见Array constructor

调试输出显示您仅填充了4个插槽,其他插槽仍为空。

答案 2 :(得分:-1)

创建一个实现该接口的类:

export interface ProfileInterface {
  id: any;
  username: any;
  profilePic: any;
}

export class Profile implements ProfileInterface {
  id = null;
  username = '';
  profilePic = null;
}

我已经测试了代码。享受编码吧!