这似乎是一个荒谬的帖子,但是最近几天我一直在尝试弄清楚如何访问嵌套的类方法。此应用程序中有两种模型,即用户模型和个人信息模型。它们的定义如下:
用户
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>
角度应用程序返回单个User对象。我尝试调用“ fullName”方法,该方法应打印串联在一起的用户的名字和姓氏。但是,出现以下错误:“ this.userInfo.fullName不是函数。(在'this.userInfo.fullName()'中,'this.userInfo.fullName'未定义)“。有什么明显的我想念的东西吗?
答案 0 :(得分:1)
问题是在反序列化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
答案 1 :(得分:0)
您必须用括号来调用fullName
,因为它是一个函数而不是属性,所以您的html应该看起来像这样
<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>