无法分配给对象“[object]”的只读属性“active”

wyyhbhjk  于 2021-09-23  发布在  Java
关注(0)|答案(2)|浏览(295)

我有下面的界面

export interface ProductCommand extends ProductDetailsCommand { }

productdetailscommand接口

export interface ProductDetailsCommand {
    id: string;
    active: boolean;
    archive: boolean;
    title: string;
    description: string;
    category: CategoryVendorCommand;
    subCategory: CategoryVendorCommand;
    tags: string[];
    vendor: CategoryVendorCommand;
}

在组件中

private productCommand: ProductCommand = {} as ProductCommand;

我正在尝试分配活动属性的值

onMenuClick(menuItem: number, id: string): void {
    switch (menuItem) {
      case 1:
        this.productCommand.active = true;
        this.productCommand.archive = null;
        this.store.dispatch(UPDATE_PRODUCT({ id: id, product: this.productCommand }));
        break;
      case 2:
        this.productCommand.active = false;
        this.productCommand.archive = null;
        this.store.dispatch(UPDATE_PRODUCT({ id: id, product: this.productCommand }));
        break;
      case 3:
        this.productCommand.active = null;
        this.productCommand.archive = true;
        this.store.dispatch(UPDATE_PRODUCT({ id: id, product: this.productCommand }));
        break;
    }
  }
}

在第二次赋值时出现异常,在第一次赋值时,我不会得到此异常,但是,在第二次赋值时,我得到此异常

ERROR TypeError: Cannot assign to read only property 'active' of object '[object Object]'
    at ProductDashboardTableComponent.onMenuClick (product-dashboard-table.component.ts:77)
    at ProductDashboardTableComponent_td_27_Template_button_click_16_listener (product-dashboard-table.component.html:82)
    at executeListenerWithErrorHandling (core.js:15272)
    at wrapListenerIn_markDirtyAndPreventDefault (core.js:15316)
    at HTMLButtonElement.<anonymous> (platform-browser.js:560)
    at ZoneDelegate.invokeTask (zone.js:406)
    at Object.onInvokeTask (core.js:28645)
    at ZoneDelegate.invokeTask (zone.js:405)
    at Zone.runTask (zone.js:178)
    at ZoneTask.invokeTask [as invoke] (zone.js:487)
``` `console.log(this.productCommand)` 在单击处理程序中:
![](https://i.stack.imgur.com/D80gX.png)
mnowg1ta

mnowg1ta1#

尝试使用扩展运算符设置值:

...
this.productCommand = {...this.productCommand, active: true};
...
but5z9lq

but5z9lq2#

productcommand,如果您正在从存储区接收此值。您需要为productcommand创建新的引用。因为存储值是只读的,所以您可以直接更改该值。

subscribe((productCommand )=>{
     this.productCommand = {...productCommand }
})

相关问题