【发布时间】:2015-11-06 23:57:25
【问题描述】:
我有这个客户类:
export class Customer {
id: number;
company: string;
firstName: string;
lastName: string;
name(): string {
if (this.company)
return this.company;
if (this.lastName && this.firstName)
return this.lastName + ", " + this.firstName;
if (this.lastName)
return this.lastName;
if (this.firstName)
return this.firstName;
if (this.id > 0)
return "#" + this.id;
return "New Customer";
}
}
在我的控制器中,我下拉了一个客户列表:
export class CustomersController {
static $inject = ["customerService", "workflowService"];
ready: boolean;
customers: Array<Customer>;
constructor(customerService: CustomerService, workflowService: WorkflowService) {
customerService.getAll().then(
(response) => {
this.customers = response.data;
this.ready = true;
},
() => {
this.ready = true;
}
);
workflowService.uiCustomer.reset();
}
}
angular.module("app")
.controller("CustomersController", ["customerService", "workflowService", CustomersController]);
如果有帮助,getAll() 看起来像这样:
getAll(): ng.IHttpPromise<Array<Customer>> {
return this.http.get("/api/customers");
}
正是这句话让我伤心:this.customers = response.data;
但是 response.data 是强类型的,所以它不应该“知道” Customer 和 name() 吗?
当我这样做时,我当然会用愚蠢的 JSON 数组覆盖我的强类型数组,它上面没有我的 name() 方法。
那么如何在不复制列表中每个对象的每个属性的情况下保留我的 name 方法?
这是我的糟糕设计吗?拥有这些只读属性在 C# 中非常常见,但我对 javascript 世界有点陌生。我应该改用实用程序类吗?
我目前的解决方法:
this.customers = response.data.map(customer => {
return angular.copy(customer, new Customer());
});
构建一个全新的数组并复制所有这些字段感觉不对(在我的真实项目中,客户有更多属性)。
编辑:我发现了一些相关的 SO 问题,例如 @xmojmr 提到的 Mapping JSON Objects to Javascript Objects。我的问题是针对 TypeScript 的,我想知道 TypeScript 是否有自己的工具可以生成 javascript 以使其成为非问题。如果不是这样,并且我们确定 TypeScript 的目的不是解决这类问题,那么我们可以认为这个问题是重复的。
【问题讨论】:
标签: javascript typescript