gpt4 book ai didi

javascript - 访问嵌套类方法

转载 作者:行者123 更新时间:2023-12-02 22:30:22 24 4
gpt4 key购买 nike

这似乎是一个荒谬的帖子,但我最近几天一直在尝试弄清楚如何访问嵌套类方法。该应用程序中有两个模型:User 模型和 PersonalInfo 模型。它们的定义如下:

用户

export class User implements Deserializable {
public id: number;
public emailAddress: string;
public username: string;
public password: string;
public userInfo: PersonalInfo;

deserialize(input: any): this {
return Object.assign(this, input);
}

get fullName() {
return this.userInfo.fullName();
}
}

个人信息

import {Deserializable} from "./deserializable.model";

export class PersonalInfo implements Deserializable {
public infoId: number;
public firstName: string;
public lastName: string;
public street: string;
public city: string;
public stateId: number;
public zipCode: string;
public mobileNumber: string;
public homeNumber: string;
public workNumber: string;

deserialize(input: any): this {
return Object.assign(this, input);
}

/**
* Return the user's full name.
*/
fullName(): string {
return this.firstName + " " + this.lastName;
}
}

** HTML 文件 **

<button class="btn-success"(click)="getUser(0)">Get User</button>
<button (click)="getUserList()">User List</button>
<div *ngIf="userList && userList.length > 0">
<table>
<thead>
<th>Username</th>
<th>Email</th>
<th>Full Name</th>
</thead>
<tbody *ngFor="let user of userList">
<td>{{user.username}}</td>
<td>{{user.emailAddress}}</td>
<td>{{user.fullName}}</td>
</tbody>
</table>

</div>

Angular 应用程序返回单个 User 对象。我尝试调用“fullName”方法,该方法应该打印连接在一起的用户的名字和姓氏。但是,我收到以下错误:“this.userInfo.fullName 不是函数。(在 'this.userInfo.fullName()' 中,'this.userInfo.fullName' 未定义)”。我是否遗漏了一些明显的东西?

最佳答案

问题是在 User 的反序列化方法中使用 Object.assign(this, input) 时。

我认为你可以重写如下

deserialize(input: any): this {
if (input["userInfo"]) {
this.userInfo =
this.userInfo == null
? new PersonalInfo().deserialize(input["userInfo"])
: this.userInfo.deserialize(input["userInfo"]);
delete input["userInfo"];
}
else
{
if (!this.userInfo)
this.userInfo=new PersonalInfo()
}
Object.assign(this, input);
return this;
}

这允许您制作,例如

this.userList.push(new User().deserialize(
{id:1,emailAddress:'qqq@qqq.com'
userInfo:{firstName:'firstName',lastName:'lastName'}
}))

参见stackblitz

关于javascript - 访问嵌套类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58924260/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com