angular – 类undecript的Typescript方法
在Typescript中,我有一个类Contact,它实现了一个接口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不是一个函数. ====更新=== 我会添加一些额外的代码来澄清一些东西. =====更新答案======== 正如Sakuto所说,联系人列表是由服务器收到的一些json创建的.通过调用它的构造函数完全创建一个新实例,我能够输出fullname属性. 解决方法
您可能正在尝试在从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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |