问题描述
我在“编辑图表组件”中有“名称和描述”输入字段。当我第一次在两个字段中都键入内容时,我没有出现错误,并且当我单击“保存”按钮时,它成功更新了两个字段,
但是当我尝试再次更改名称和描述字段并开始输入时,出现此错误(图片)。关于如何解决此问题的任何建议或想法,将不胜感激。
现在,只有遵循这样的步骤,我才不会出现错误,
更新了两个字段->转到其他页面->返回并再次更新
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});
}
}
解决方法
似乎您无法更改商店的属性,因为它是只读的。
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)