2017-09-16 73 views
1

我有一個數組名稱菜,並有一個窗體。在表單提交後,數據推到盤上。我試圖用push方法將它添加到數組中,但它有錯誤。我如何用打字稿做到這一點? 非常感謝。 類對象。如何將對象推入與打字稿數組

export interface Dish { 
    id: number; 
    name: string; 
    image: string; 
    category: string; 
    label: string; 
    price: string; 
    featured: boolean; 
    description: string; 
    comments: Comment[]; 
} 

我已經創建了類註釋中的對象名稱commentData,以便在提交後從表單接收所有數據。我還創建了Dish類的對象名稱菜。如何推動對象commentData反對dish.comments

export interface Comment { 
    rating: number; 
    comment: string; 
    author: string; 
    date: string; 
} 

我的git:https://github.com/zymethyang/Ionic_HKUST

+0

請添加有關對象的代碼。 –

+0

我已編輯我的帖子。請檢查頂部。謝謝。 –

回答

1
let myArray= []; 
let commentData = {} as Dish; 
commentData.id = 3; 
commnetData.name = 'something'; 
... 

myArray.push(commentData); 

它將工作...

+0

對不起,但我有一個新的評論,並希望推到現有的dish.comments。 –

1

如果你只需要每個表格後,添加新commentData提交(如果我理解正確的你),你所需要的,這是你想要的新的評論被推向現有dish.comments每次

this.dish.comments = this.dish.comments.push(this.commentData); // assuming these are class properties, hence the 'this' usage 

這是否適合您?

EDIT

修改第一線

this.commentData = this.comment.value; 
dismiss()方法本

this.commentData.author = this.comment.get('author').value; 
this.commentData.rating = this.comment.get('rating').value; 
this.commentData.comment = this.comment.get('comment').value; 
+0

是的,這就是我想要的,但它不起作用。 [ts]類型'數字'不可分配給類型'Comment []'。 (財產)Dish.comments:評論[] –

+0

有趣,哪裏了'number'從何而來?你可以顯示你的commentData對象的例子嗎? – amal

+0

commentData對象的示例。 「想象所有的食物,生活在混亂中!」, 「作者」:「約翰·萊蒙」, 「約會」:「2012-10-16T17:57: 28.556094Z」 }' –

0

let arraylist= [];
let obj1 = {} as Class;
obj1.id = 1;
obj1.name = 'text';
let obj2 = {} as Class;
obj2.id = 1;
obj2.name = 'text';
arraylist =[obj1,obj2 ];

這爲我工作,但我有類試了一下