簡體   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