我有一個組件在訂閱的頁面上顯示一些數據。Angular2 - 克隆變量以不修改源
我正在嘗試clone
該變量並對其進行更改,而不會影響用於呈現頁面視圖的原始數據。
import { UtilsService } from '../shared';
import { Component, Input, OnInit } from '@angular/core';
@Component({
selector: 'app-review',
templateUrl: './review.component.html',
styleUrls: ['./review.component.css']
})
export class ReviewComponent implements OnInit {
@Input() payload: any = null;
// Object of strings that are used for the details
langStr: any = {
noDepartment: 'No Department Change',
noSegment: 'No Segment Change',
noMarket: 'No Budget Market Change',
noIncentive: 'No Incentive Plan Change',
noRole: 'No Role Change',
noProductionDate: 'No Production Date Change',
noLanguage: 'No Language Change',
noShift: 'No Shift Change',
noSupervisor: 'No Supervisor Change'
};
// Used to scan through the final payload and assign default values if missing
optionalFields = ['budgetMarket',
'hierarchy',
'incentivePlan',
'primaryLanguage',
'secondaryLanguage',
'role',
'segment',
'shiftID',
'supervisor'];
modifiedData: any;
constructor(
private utils: UtilsService
) {
}
ngOnInit() { }
submitChanges() {
this.modifiedData = this.payload;
// Loop over all of the keys in our formData object
for (const key in this.modifiedData.formData) {
// Find shift by property if the key exists within our defined array
if (this.modifiedData.formData.hasOwnProperty(key) && this.utils.isInArray(this.optionalFields, key)) {
// If our object data doesnt have a value, set it to -1
if (!this.modifiedData.formData[key].length) {
this.modifiedData.formData[key] = '-1';
}
}
}
// Send to database
console.log(this.modifiedData)
}
}
在上面這種情況下,我想我的認購this.payload
數據設置爲一個名爲modifiedData
新的變量。然後,我修改了該作業中的一些數據。
但是,只要我調用函數submitChanges()
,我的HTML視圖就會對modifiedData
所做的更改進行更新,即使它未訂閱該更新。
我認爲這是this.modifiedData = this.payload;
以某種方式更新原始數據()。
有沒有辦法做到這一點,其中不會被觸及。我基本上只是克隆它,並在將其提交給我的數據庫調用之前進行一些更改。
不是重複的,因爲他沒有詢問如何克隆,而是因爲他的代碼中的錯誤,這是因爲在引用方面如何處理對象。雖然 – lexith