如何修复无法分配为Angular中的只读属性

问题描述

我在“编辑图表组件”中有“名称和描述”输入字段。当我第一次在两个字段中都键入内容时,我没有出现错误,并且当我单击“保存”按钮时,它成功更新了两个字段,

但是当我尝试再次更改名称和描述字段并开始输入时,出现此错误(图片)。关于如何解决此问题的任何建议或想法,将不胜感激。

现在,只有遵循这样的步骤,我才不会出现错误,
更新了两个字段->转到其他页面->返回并再次更新

HTML

<mat-form-field>
    <mat-label>Title</mat-label>
    <input matInput [(ngModel)]="chart.name" placeholder="Title" required>
</mat-form-field>

<mat-form-field>
    <mat-label>Description</mat-label>
    <textarea matInput [(ngModel)]="chart.description" placeholder="enter description"></textarea>
</mat-form-field>

TS

 chart: Chart;

  ngOnInit(): void {
    this.loading$ = this.store.pipe(select(selectChartLoading)).pipe(takeUntil(this.death$),tap(val => console.log('LOADING:',val)));
    this.store.pipe(select(selectChart)).pipe(takeUntil(this.death$),tap(val => console.log('CHART:',val))).subscribe(chart => {
      if (!chart) return;
      this.chart = new Chart(chart);

    this.store.pipe(select(selectWorkspace)).pipe(takeUntil(this.death$)).subscribe(ws => {
      this.workspace = ws;
    });
  }

  saveClick() {
    if(this.chart.name.length > 0 && this.chart.description.length > 0){
      this.store.dispatch(updateChart({ chart: this.chart,chartData: undefined,validateData: false }));
    }
    else{
      this.snackbar.open("Error: Chart name and description is required","",{duration: 2500});
    }
}

enter image description here

解决方法

似乎您无法更改商店的属性,因为它是只读的。

this.store.pipe(select(selectChart)).pipe(takeUntil(this.death$),tap(val => console.log('CHART:',val))).subscribe(chart => {
      if (!chart) return;
      this.chart = new Chart({...chart}); // change the line here

    this.store.pipe(select(selectWorkspace)).pipe(takeUntil(this.death$)).subscribe(ws => {
      this.workspace = ws;
    });

尝试通过扩展this.chart来将...分配更改为不同的内存位置。

此外,嵌套的subscribes也不是很好。我会这样更改您的信息流:

import { filter,switchMap } from 'rxjs/operators';
....
this.store.pipe(select(selectChart)).pipe(
  tap(val => console.log('CHART:',val)),filter(chart => !!chart),// chart has to be truthy,or else this stream won't continue
                            // we can therefore get rid of the if (!chart) return;
  switchMap(chart => {
           this.chart = new Chart({...chart});
           return this.store.pipe(select(selectWorkspace)); // switch to this observable
 }),takeUntil(this.death$),// take subscriptions until death$ emits
).subscribe(chart => {
      this.workspace = ws;
  });
,

我不确定什么是Chart,但我认为您将需要更深的Chart副本,因为散布运算符只会生成浅表副本。看看lodash的cloneDeep

您可以执行以下操作:this.chart = cloneDeep(chart)

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...