Angular ngrx:分配只读 属性

Angular ngrx: assign a readonly property

我正在使用 Ngrx 构建 Angular 应用程序,但我遇到了问题。这是:

在 OnInit 中,我启动调度器和选择器以从商店获取我的数据,我想编辑这些数据。
当我尝试这样做时,出现错误“无法分配给对象‘[object Object]’的只读 属性 'title'”: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();
        });

}

编辑: 我曾尝试像这样在订阅中编辑我的数据,但得到了同样的错误:

    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();
        });
}