繁体   English   中英

如何在打字稿中将新值传递到新创建的对象中

[英]how to pass a new value into a newly created object in typescript

我正在使用Angular 6和数组一起工作。 我有一个数组和一个模型。

阵:

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"
    },
]

模型:

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;
    }
}

如您所见,模型中有一个名为“ index”的参数。 当从此数组中选择一个项目时,我将使用此方法创建一个新对象。

selectItem(index, data){
    let selectedItem = new Data(data);
    console.log(selectedItem);
}

如预期的那样,结果是:

{
    id: 1,
    value: "Some Value",
    description: "Some Description"
}

在这种情况下,我无法将索引值添加到新创建的对象中,因为数据对象没有此参数。

这就是为什么我用

selectItem(index, data){
   let selectedItem = new Data({
       index = index,
       id = data.id,
       value = data.value,
       description = data.description
   })
}

我的问题是:有没有一种方法可以在使用模型创建新对象时添加其他参数。 我需要这样的东西。

selectItem(index, data){
    let selectedItem = new Data({data}).index = index
}

我会为您的构造函数创建一个可选参数。

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;
  }
}

然后,您可以完全根据需要进行操作

selectItem(index, data){
  let selectedItem = new Data(data, index);
}

但是如果需要,也可以创建没有它的对象

let selectedItem = new Data(data);

您不能在Data类中创建新的对象Data。 您可以尝试以下方法:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM