在Typescript中,我有一个类Contact,它实现了一个接口IContact.
我想向Contact类添加一个属性或函数,它返回另外两个字段(firstname和lastname)的组合.
IContact接口的定义如下所示:
我想向Contact类添加一个属性或函数,它返回另外两个字段(firstname和lastname)的组合.
IContact接口的定义如下所示:
export interface IContact { firstname: string; lastname: string; }
Contact类看起来像这样:
export class Contact implements IContact { constructor( public firstname: string,public lastname: string ) { } public fullname(): string { return this.firstname + " " + this.lastname; } }
在我看来,我想输出Contact.fullname()的结果,但是我收到一个错误,即fullname不是一个函数.
我可以访问该类的所有其他属性.
====更新===
我会添加一些额外的代码来澄清一些东西.
当我在视图中输出fullname属性时,我尝试了contact.fullname(),但也联系了.fullname,结果什么都没有.
在我的组件中,试图弄清楚发生了什么我尝试将fullname输出到控制台,如下所示:console.log(“FULLNAME”contact.fullname());,但是在控制台中给出了以下消息:EXCEPTION _this .contact.fullname不是函数
=====更新答案========
正如Sakuto所说,联系人列表是由服务器收到的一些json创建的.通过调用它的构造函数完全创建一个新实例,我能够输出fullname属性.
谢谢Sakuto!
解决方法
您可能正在尝试在从JSON动态转换的对象上调用此方法.动态铸造的对象没有在类中定义的方法,它们只是尊重合同并拥有属性.
使当前代码工作的唯一方法是创建一个新的Contact实例,而不是仅使用< Contact>转换它. yourObject;
解决方案是做这样的事情:
let contactsList: Contact[] = []; yourServiceReturn.ForEach(c => contactsList[] = new Contact(c.name,c.surname)); // You can now call getFullName on the object stored on contactsList