Angular 2实例化类具有空值 [英] Angular 2 instantiate class with empty values
问题描述
如何将成员实例化为具有空值的类?
How do you instantiate the members as class with empty values?
Plunkr
我用
public members = new MemberClass();
但是控制台显示Member:{},所以我无法设置默认的空值
but the console shows Members: {} so I'm unable to set the default empty values
所以基本上我正在尝试复制一个空结构,如:
so basically I'm trying to replicate an empty structure like:
this.members = [
{
"Name" : "", "Id" : "", "Team" : "",
"Cases" : {
"history" : []
}
}
];
推荐答案
使用接口;)这是一种可以创建带有属性设置为Member
的空对象的Array的方法.我不知道用例,至少我没有为空对象/模型数组设置属性,但是我们开始:)
Use interfaces ;) And this is a way you can create an Array with an empty object of type Member
with properties set. I don't know the use case, at least I do not set the properties for empty objects/arrays of models, but here we go :)
首先,您的界面是:
export interface Member {
Id: string;
Name: string;
Cases: Case[];
}
export interface History {
Id: string;
CaseNumber: string;
}
export interface Case {
History: History[];
}
然后您创建3个函数来设置属性:
Then you create 3 functions to set the properties:
export function createMember(Id?:string,Name?:string, Cases?:Case[]): Member {
return {
Id,
Name,
Cases[createCase()]
}
}
export function createCase(History?:History[]): Case {
return {
History[createHistory()]
}
}
export function createHistory(Id?: string,CaseNumber?:string): History {
return {
Id,
CaseNumber
}
}
现在您可以在组件中调用函数createMember
,然后调用其他两个函数:
And now in your component you can call the function createMember
, that then calls the two other functions:
members = [createMember()];
PS,根据您的模型,以下不是Member
-array的模型,它们的名称和构建不匹配,但是我是根据您提供的模型创建的.
PS, according to your models, the following is not the model of Member
-array, they name and build doesn't match, but I have created the above, based on the models you have provided.
这篇关于Angular 2实例化类具有空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!