首页 > 解决方案 > 类型错误:“值”是只读的

问题描述

我正在尝试使用 ngrx 存储将数据发送到我的后端,但出现此错误:ERROR TypeError: "value" is read-only。我尝试了很多东西,但没有一个奏效。

我必须发送包含刚刚修改的属性数组的“设备”对象,相关设备已在商店中注册,我直接从组件中的商店获取它以制作我的表格

我的效果代码:

updateEquipment$ = createEffect(() =>
    this.actions$.pipe(
      ofType(SettingsActions.updateEquipment),
      switchMap(action => {
        const equipment = { ...action.equipment };
        // const result = { ...action.gasxProperty };
        action.gasxProperty.forEach(res => {
          equipment.properties.find(prop => prop.name === res.name).value = res.value; // <== here i get the error
        });
        return this.settingsService.saveEquipment(action.equipment).pipe(
          map(equipmentSaved => {
            this.store.dispatch(CoreActions.hideSpinner());
            this.toastrService.success('', 'Equipement sauvegardée.');
            return SettingsActions.updateEquipmentSuccess({ equipment: equipmentSaved });
          }),
          catchError(() => {
            this.store.dispatch(CoreActions.hideSpinner());
            this.toastrService.error('', 'Erreur de sauvegarde.');
            return of(SettingsActions.updateEquipmentError());
          })
        );
      })
    )
  );

在我的组件上,我这样做是为了保存:

public equipment$: Observable<Equipment>;

constructor() {
    this.equipment$ = this.store.select(fromSettings.getSelectedEquipment);
  }

        public onSubmit(equipment: Equipment): void {
          const result = Object.keys(this.form.controls.gasx.value).map(key => ({
            name: key,
            value: this.form.controls.gasx.value[key]
          }));
          result.pop();
          this.store.dispatch(CoreActions.showSpinner());
          this.store.dispatch(SettingsActions.updateEquipment({ equipment, gasxProperty: result }));
      }

的HTML:

<ng-container *ngIf="(equipment$ | async) as equipment">
      <div *ngIf="!isEditable"
        (click)="turnOnCheckbox(equipment)"
        class="flex items-center justify-center w-8 h-8 rounded-full bg-smg-lightGray">
        <img class="w-3 cursor-pointer"
          src="../../../../../../assets/icons/pen.svg" />
      </div>
    </ng-container>

行动是:

export const updateEquipment = createAction(
  '[Settings] Update equipment',
  props<{ equipment: Equipment; gasxProperty }>()
);

有任何想法吗?

标签: typescriptngrx

解决方案


您不能这样做,因为该操作已“冻结”(只读)。

action.gasxProperty.forEach(res => {
  equipment.properties.find(prop => prop.name === res.name).value = res.value; // <== here i get the error
});

相反,您应该以不可变的方式更新它(使用扩展语法


推荐阅读