[英]How do I cast a list of JSON objects into a list of TypeScript objects without losing properties on the TypeScript class?
我有這個Customer類:
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()方法。
那么如何在不復制列表中每個對象的每個屬性的情況下保留我的名稱方法呢?
這是我的壞設計嗎? 擁有這些只讀屬性在C#中非常常見,但我對javascript世界有點新鮮。 我應該使用實用程序類嗎?
我目前的解決方法:
this.customers = response.data.map(customer => {
return angular.copy(customer, new Customer());
});
構建一個全新的數組並復制所有這些字段感覺不對(在我的真實項目中,Customer有更多的屬性)。
編輯:我發現了一些相關的SO問題,比如@xmojmr提到的將JSON對象映射到Javascript對象 。 我的問題是特定於TypeScript的,我想知道TypeScript是否有自己的任何設施可以生成javascript以使其成為非問題。 如果情況並非如此,並且我們確信TypeScript不是為了解決這類問題,那么我們可以將此問題視為重復。
你對發生的事情是完全正確的。 鍵入typescript主要為您提供編譯器檢查。 在封面下,所有內容都編譯為JavaScript,而不是強類型。
所以,當你說:
getAll(): ng.IHttpPromise<Array<Customer>> {
return this.http.get("/api/customers");
}
所有你真正在做的就是告訴編譯器“嘿,我很確定我的api端點將返回一個Customer
對象數組。” 但是如你所知,它實際上只返回一個“啞的JSON”數組。
您可以考慮做的是創建一個描述API端點返回的JSON對象的接口。 就像是:
interface ICustomer {
id: number;
company: string;
firstName: string;
lastName: string;
}
然后getAll()
變為:
getAll(): ng.IHttpPromise<Array<ICustomer>> {
return this.http.get("/api/customers");
}
然后你可以讓一個類的構造函數將ICustomer
作為參數。 或者您可以使用靜態方法創建一個類,該方法接受ICustomer
並返回“name”。
顯然,你現在正在做的事情是有效的,但我認為你正在尋找能夠更好地傳達意圖的東西。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.