我正在用Ngrx构建一个Angular App,我遇到了一个问题。问题是这样的:在OnInit中,我启动了dispatch和selector,用于从商店获取数据,我想编辑这些数据。
在OnInit中,我启动了dispatch和selector来从商店获取数据,我想编辑这些数据。当我尝试这样做的时候,我得到了一个错误 "Cannot assign to read only property 'title' of object '[object Object]'': x.title = '[对象对象]'。${x.title} (${count})
我明白为什么我不能重新分配,状态是不可改变的。是的,但我如何编辑我的数据?我一开始是在效果里做的,但这是显示逻辑,我想我必须在组件逻辑里做。
这是我的OnInit函数。
ngOnInit() {
this.store.dispatch(new GetAllProducts());
this.store.select(selectResourcesList).pipe(
distinctUntilChanged((a, b) => JSON.stringify(a) === JSON.stringify(b))
)
.pipe(tap((res => {
res.resources.map(x => {
let count = 0;
res.events.map(y => {
if (y.resourceId === x.id) {
count += y.extendedProps.quantity;
return count;
}
return count;
});
x.title = `${x.title} (${count})`;
});
})))
.subscribe((res) => {
this.resources = res.resources;
this.events = res.events;
this.cdr.detectChanges();
});
}
edit:I had try to edit my data in the subscribe like this, but get the same error:
ngOnInit() {
this.store.dispatch(new GetAllProducts());
this.store.select(selectResourcesList).pipe(
distinctUntilChanged((a, b) => JSON.stringify(a) === JSON.stringify(b)))
.subscribe((res) => {
const tempResources = [...res.resources];
const tempEvents = [...res.events];
tempResources.map(x => {
let count = 0;
tempEvents.map(y => {
if (y.resourceId === x.id) {
count += y.extendedProps.quantity;
}
});
x.title = `${x.title} (${count})`;
});
this.resources = tempResources;
this.events = tempEvents;
this.cdr.detectChanges();
});
}
先谢谢你的帮助;-)
我找到了一个绕过存储不可变性的解决方案。
我必须创建一个选择器结果的副本(用传播操作符),然后在上面做修改。
就像这样,我必须创建一个选择器结果的副本(使用传播操作符),并对其进行修改。
ngOnInit() {
this.store.dispatch(new GetAllProducts());
this.store.select(selectResourcesList).pipe(
distinctUntilChanged((a, b) => JSON.stringify(a) === JSON.stringify(b)))
.subscribe((res) => {
let tempResources = [...res.resources];
let tempEvents = [...res.events];
tempResources = tempResources.map(x => {
let count = 0;
tempEvents = tempEvents.map(y => {
if (y.resourceId === x.id) {
count += y.extendedProps.quantity;
}
return y;
});
x = {
...x,
title: `${x.title} (${count})`
};
return x;
});
this.resources = tempResources;
this.events = tempEvents;
this.cdr.detectChanges();
});
}