Angular NgRx 存储类型错误:无法分配给对象“[object Object]”的只读属性“primary”

问题描述 投票:0回答:2

我在 NgRx 存储中有一个对象数组,如下所示:

[ {email: '[email protected]', primary: true, type: 'WORK'}, 
  {email: '[email protected]', primary: true, type: 'WORK'}, 
  {email: '[email protected]', primary: true, type: 'WORK'} ]

从商店检索数据时,我将上述数组分配到组件内的属性中。

我使用上述数据循环遍历 HTML 元素,用现有信息填充它们

*ngFor

当我尝试更改数据时(例如单击按钮将特定“主”键的值转换为相反的值(即 true 变为 false,false 变为 true)),则由于以下错误,数据无法更改:

TypeError: Cannot assign to read only property 'primary' of object '[object Object]'

以下是代码:

// Get data from store and assign to local property
this.myData = this.store$.existingData;

<div class="form-element" *ngFor="let email of myData; let index = index">
    <input type="text" placeholder="Email Address" [(ngModel)]="email['email']" />
</div>

我尝试将 this.myData 重新分配给另一个属性,然后循环遍历该属性,以及使用 Object.assign 从存储中获取数据并将其放入 this.myData 属性中,但同样的错误不断发生。

我完全意识到存储中的数据是不可变的,除非在减速器中进行管理(并且这不会发生任何问题)。

我尝试过查看类似性质的其他答案,但似乎没有人遇到完全相同的问题。

如何从商店获取数据,将其分配给本地属性,并更改该数据而不发生上述错误?

更新1:

附加数据

this.StoreSubscription = this.store.subscribe(state => {
      this.store$ = state.consumer;
    });
angular typescript ngrx ngrx-store
2个回答
10
投票

您的问题是

ngModel
。在不了解有关代码的任何其他信息的情况下,您应该执行类似的操作,否则
ngModel
指令会尝试写入不可变电子邮件数据对象中的值:

<input [ngModel]="email['email']" (ngModelChange)="onEmailChange(email, $event)">


onEmailChange(email: EmailData, newEmail: string): void {
  // call action to store to update email object with `newEmail` in store
}

要使您的对象不再是不可变的(浅层),您可以执行以下操作:

this.myData = this.store$.existingData.map((email) => ({ ...email }));

0
投票

也有类似的问题。设法通过传递对象的克隆而不是引用来修复它。

    this.store.select('recipes').subscribe(
    recipes=>{
      this.recipes = Object.assign({}, recipes);
    }
  );
this.route.params.subscribe(
    (params: Params)=>{
  this.recipe = Object.assign({}, this.recipes[this.selectedRecipeIndex]);
© www.soinside.com 2019 - 2024. All rights reserved.