2017-04-13 47 views
0

我正在使用反應形式,並且在理解數據如何映射到窗體控件時遇到了一些麻煩。我們來看一個具有id和名字的對象控件的例子。此控件應呈現爲輸入文本框,並且用戶鍵入Id。我然後使用自動填充功能以遠程查找的對象,並使用看起來像這樣在具有函數的打字稿類中捕獲json數據

{ id: 1234, description: "Some description" } 

由於,這是一個對象,而不是一個字符串數據填充底層對象 - 在輸入框中顯示[對象的對象如它的價值。我假設我需要爲此對象提供toString方法,以便能夠顯示像這樣的值1234 - Some description

這裏是形式配置:

this.orderForm = this.fb.group({ 
    customer: '', 
    .... 
    items: this.fb.array([ this.initItems() ]) 
    ... 

所以customer是這些對象中的一個和另一個類似的對象是item對象上。

export class Customer { 
    id: string; 
    descr: string; 
    toString =() => this.id + " - " + this.descr 
} 

export class ItemDetail { 
    id: string; 
    descr: string; 
    toString =() => this.id + " - " + this.descr 
} 

export class Order { 
    id: string; 
    ... 
    customer: Customer; 
    items: Item[] 
} 

export class Item { 
    ... 
    detail: ItemDetail 
    ... 
} 

一旦我有訂單數據,我加載它的形式是這樣的:

const itemsFGs = order.items.map(item => this.fb.group(item)); 
const itemsFA = this.fb.array(itemsFGs); 
this.orderForm.setControl('items', itemsFA); 

的問題是,加載數據作爲普通對象而不是類型強制轉換爲相應的類,因此,在任何嵌套對象上都沒有toString方法,這使得輸入框顯示[object Object]而不是使用toString方法。

下面是一個樣本順序JSON的樣子:

{ 
    id: "1", 
    customer: { 
    id: "1", 
    name: "some customer" 
    }, 
    items: [{ 
    detail: { 
     id: "1", 
     descr: "some item" 
    } 
    }] 
} 

主要的問題是,我怎麼能確保未來在爲JSON數據在適當的類別被捕獲讓喜歡的toString方法可用於正確顯示。

回答

0

注意:當您在打字稿中創建複雜對象類型時,請始終使用界面。

export interface Customer { 
    id: string; 
    descr: string; 
} 

此外,如果你不能確定從服務傳來的參數,你期待一個未定義的錯誤,使用下面的代碼作爲可選指定的那些屬性,

export interface ItemDetail { 
    id: string; 
    name: string; 
    descr?: string; //optional 
} 

export interface Order { 
    id: string; 
    ... 
    customer: Customer; 
    items: Item[] 
} 
export interface Customer{ 
    id:string; 
    name: string; 
    address?: string; //optional 
    dob?: Date;  //optional 

}

通過這可以避免可選參數綁定到實際對象,如果它們不在響應中。當這些屬性在服務響應中可用時,它們如何按預期進行綁定。

更新1:

你應該做分組

this.form = this.fb.group({ 
     firstName: ['', [Validators.required, Validators.minLength(3)]], 
     lastName: ['', [Validators.required, Validators.minLength(3)]], 
     customerGroup :this.fb.group({ 
       firstName: ['', [Validators.required, Validators.minLength(3)]], 
       lastName: ['', [Validators.required, Validators.minLength(3)]], 
     }, {validator: Validators.required}) 
     .... 
    }); 
+0

這聽起來不錯,我會嘗試了這一點,但在界面,你無法定義方法的另一個層次,我想指定這些內部對象的tostring方法,以便它們在輸入文本框中正確顯示。有關如何做到這一點的任何建議? – adeelmahmood

+0

toString()會對文本框做些什麼? – Aravind

+0

可以說客戶對象有這個數據{{id:1,name:'abc'}'。如果我使用[formControl] =「customer」將此對象綁定到輸入文本框,則輸入框將顯示[object Object]作爲其值。我想展示類似'1 - abc'的信息 – adeelmahmood