[英]how to pass a new value into a newly created object in typescript
I am using Angular 6 an working with arrays. 我正在使用Angular 6和数组一起工作。 I have an array and a model.
我有一个数组和一个模型。
Array: 阵:
let array = [
{
id: 1,
value: "Some Value",
description: "Some Description"
},
{
id: 2,
value: "Some Value",
description: "Some Description"
},
{
id: 3,
value: "Some Value",
description: "Some Description"
},
]
Model: 模型:
export class Data{
index: number;
id: number;
value: string;
description: string;
constructor(data){
this.index = null;
this.id = data.id;
this.value = data.value;
this.description = data.description;
}
}
As you see there is a parameter in the model named "index". 如您所见,模型中有一个名为“ index”的参数。 When an item is selected from this array, I create a new object with this method.
当从此数组中选择一个项目时,我将使用此方法创建一个新对象。
selectItem(index, data){
let selectedItem = new Data(data);
console.log(selectedItem);
}
As expected the result is: 如预期的那样,结果是:
{
id: 1,
value: "Some Value",
description: "Some Description"
}
In this case I can't add the index value into the newly created object because data object doesn't have this parameter. 在这种情况下,我无法将索引值添加到新创建的对象中,因为数据对象没有此参数。
That's why I use 这就是为什么我用
selectItem(index, data){
let selectedItem = new Data({
index = index,
id = data.id,
value = data.value,
description = data.description
})
}
My question is: Is there a way for adding additional parameters while creating a new object with models. 我的问题是:有没有一种方法可以在使用模型创建新对象时添加其他参数。 I need something like this.
我需要这样的东西。
selectItem(index, data){
let selectedItem = new Data({data}).index = index
}
I would create an optional parameter for your constructor. 我会为您的构造函数创建一个可选参数。
export class Data{
index: number | null;
id: number;
value: string;
description: string;
constructor(data, index: number | null = null){
this.index = index;
this.id = data.id;
this.value = data.value;
this.description = data.description;
}
}
And then later on you can do exactly as you need 然后,您可以完全根据需要进行操作
selectItem(index, data){
let selectedItem = new Data(data, index);
}
But it's also possible to create an object without it if you need 但是如果需要,也可以创建没有它的对象
let selectedItem = new Data(data);
You cant create a new object Data in the class Data. 您不能在Data类中创建新的对象Data。 You can try this:
您可以尝试以下方法:
export interface IData {
index: number;
id:number;
value:string;
description:string
}
selectItem(index, data):IData{
let result:IData = {
index: index,
id: this.id,
value: this.value,
description: this.description
};
return result;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.