打字稿的代码批次未同步执行

时间:2018-07-18 15:28:52

标签: json angular typescript angular5 synchronous

当通过参数更改其值的函数将其传递给JSON对象数组时,我遇到了问题。 在执行函数之前,它正在更改其值。

函数parseTableDataAndHeaders包含两个JSON对象数组,一个是来自表的数据数组,另一个是包含表头的数组,然后它将头objectKey替换为表数据数组上的名称。

问题在于表数据数组在执行之前发生了变化,我不知道为什么。

表数据数组定义:

table = [
  {
    id: 1,
    storeLocation: '9638 Airline Hwy, Suite B2B',
    storeId: 1,
    storeCity: 'Baton Rouge',
    storeState: 'LA'
  },
  {
    id: 2,
    storeLocation: '1651 Lamar St, Suite A',
    storeId: 2,
    storeCity: 'Houston',
    storeState: 'TX'
  },
  {
    id: 3,
    storeLocation: '5875 Main St, Suite D',
    storeId: 3,
    storeCity: 'Zacary',
    storeState: 'LA'
  },
  {
    id: 4,
    storeLocation: '9638 Airline Hwy, Suite B2B',
    storeId: 4,
    storeCity: 'Houston',
    storeState: 'LA'
  },
  {
    id: 5,
    storeLocation: '9638 Airline Hwy, Suite B2B',
    storeId: 5,
    storeCity: 'Houston',
    storeState: 'LA'
  },
];

表头数组定义:

tableColumns = [
  {
    name: 'Store Location',
    objectKey: 'storeLocation'
  },
  {
    name: 'Store ID',
    objectKey: 'storeId'
  },
  {
    name: 'City',
    objectKey: 'storeCity'
  },
  {
    name: 'State',
    objectKey: 'storeState'
  }
];

parseTableDataAndHeaders函数定义:

parseTableDataAndHeaders(jsonTableData: any[], jsonTableHeaders: any[]) {
const tableData: any[] = jsonTableData;
const tableHeaders: any[] = jsonTableHeaders;

tableData.forEach(item => {
  Object.keys(item).forEach(itemKey => {
    if (typeof item[itemKey] !== 'string') {
       item[itemKey] = item[itemKey].toString();
    }

    if (itemKey === 'id') {
      delete item[itemKey];
    }

    tableHeaders.forEach(header => {
      if (itemKey === header['objectKey']) {
        item[header['name']] = item[itemKey];
        delete item[itemKey];
      }
    });
  });
});

return tableData;

}

我遇到的这批代码:

ngOnInit() {
  console.log('Before execution');
  console.log(this.table);

  this.parsedTableData = this.parseTableDataAndHeaders(this.table, this.tableColumns);

  console.log('After execution');
  console.log(this.table);
}

控制台日志:

https://i.stack.imgur.com/Idvau.jpg

0 个答案:

没有答案