Angular NgRx存储类型错误:无法分配给只读属性';初级';对象的';[对象对象]';
我在NgRx存储中有一组对象,如下所示:Angular NgRx存储类型错误:无法分配给只读属性';初级';对象的';[对象对象]';,angular,typescript,ngrx,ngrx-store,Angular,Typescript,Ngrx,Ngrx Store,我在NgRx存储中有一组对象,如下所示: [ {email: 'firstemail@domain.com', primary: true, type: 'WORK'}, {email: 'secondemail@domain.com', primary: true, type: 'WORK'}, {email: 'thirdemail@domain.com', primary: true, type: 'WORK'} ] 从存储中检索数据时,我将上述数组分配到组件内的属性中 我使
[ {email: 'firstemail@domain.com', primary: true, type: 'WORK'},
{email: 'secondemail@domain.com', primary: true, type: 'WORK'},
{email: 'thirdemail@domain.com', 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>
您的问题是
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
}
谢谢你的回答,波尔。不幸的是,我刚刚尝试添加了这个,同样的错误仍然存在,因为ngModel仍然存在。我创建的ngModelChange函数甚至没有启动,因为由于前面提到的错误,数据拒绝更改。在我的研究过程中,问题似乎是来自NgRx存储的数据分配正在复制对象,包括对象的不变性(例如“配置:false”,“可写:false”)。我需要从可写的存储中获取对象的副本。@Jamiebohana你能演示一下如何在组件ts中获取数据吗?嘿,我添加了额外的数据,但实际上只是从NgRx存储中获取数据。你是一个绝对的神!非常感谢你!我花了几个小时试图找到解决这个问题的办法!我不需要使用ngModelChange来修复此问题。只是对象的浅克隆。太神了
<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 }));