我有以下資料結構:
uiBundles:
[
{
"id": "tasks widget UI",
"uiUnits": [
{
"type": "widget",
"id": "tasks-widget",
"roles": "MB"
}
]
},
{
"id": "berater widget UI",
"uiUnits": [
{
"type": "widget",
"id": "berater-widget",
"roles": "MB"
}
]
}
]
我想要做的是將一個新的 uiUnit 添加到這個嵌入的物件陣列中。這是我的代碼:
添加-new.component.ts:
uiBundles: UIBUndle[];
ngOnInit(): void {
this.getBundlesService.getUiBundles().subscribe((value: UIBundle[]) => this.uiBundles = value);
}
addWidget(id: string): void {
this.selectedUiUnits = this.uiBundles.filter((data) => data.id === id);
let newWidget = { id: 'new', uiUnits: [{ id: 'new-widget', type: 'widget', roles:'MB' }] };
}
添加-new.component.html:
<div *ngFor="let bundle of uiBundles">
<button (click)="addWidget(bundle.id)"></button>
</div>
當我運行這段代碼時,結果是這樣的:
[
{
"id": "tasks widget UI",
"uiUnits": [
{
"type": "widget",
"id": "tasks-widget",
"roles": "MB"
}
]
},
{
"id": "berater widget UI",
"uiUnits": [
{
"type": "widget",
"id": "berater-widget",
"roles": "MB"
}
]
},
{
"id": "new",
"uiUnits": [
{
"type": "widget",
"id": "new-widget",
"roles": "MB"
}
]
}
]
但我想做的是:
[
{
"id": "tasks widget UI",
"uiUnits": [
{
"type": "widget",
"id": "tasks-widget",
"roles": "MB"
},
{
"type": "widget",
"id": "new widget",
"roles": "MB"
}
]
},
{
"id": "berater widget UI",
"uiUnits": [
{
"type": "widget",
"id": "berater-widget",
"roles": "MB"
}
]
}
]
有人可以幫助我嗎,我在這里做錯了什么?
uj5u.com熱心網友回復:
您不是將新的小部件添加到具有指定 id 的小部件的 uiUnits 陣列中,而是創建一個全新的小部件。
你想要的是
addWidgetToBundleUnits(id: string) {
const selectedBundle = this.uiBundles.find(bundle => bundle.id === id);
const widgetToAdd = {id: 'new-widget', type: 'widget', roles: 'MB'};
selectedBundle.uiUnits.push(widgetToAdd);
}
uj5u.com熱心網友回復:
試試這個:
addWidget(id: string): void {
const index: number = this.uiBundles.findIndex((data) => data.id === id);
const newUnits = [{ id: 'new-widget', type: 'widget', roles:'MB' }];
this.uiBundles[index].uiUnits.push(newUnits);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/380915.html
