首页 > 解决方案 > 替换集合中实体的最简洁方法

问题描述

实体适配器支持使用“updateOne”方法调用更新集合。但是,当更新值的键不存在时,这会导致特定实体不被更新。请参阅代码示例。

但是,在内部,实体适配器使用Object.assign()which while is nice 并不总是我想要的。我希望它基本上取代有问题的实体。

此外,如果所讨论的对象具有结构 A(见下文)。然后发生了一些任意的数据库操作并将更新的 JSON 返回到前端。reducer 最终会在表单中获得该信息。

const originalValue: MyClass = new MyClass('value 1', 'value 2');
const updatedValueFromServer: MyClass = new MyClass('updated');
Then internally to the entity adapter it looks like 

const updateValue = Object.assign(originalValue, updatedValueFromServer);
// which would result in ...
// { key1: 'updated', key2: 'value 2' }
// while I would like
// { key1: 'updated' }
// Or 
// { key1: 'updated', key2: null }
case ActionTypes.UPDATE_SUCCESS:
            return collectionAdapter.updateOne({
                changes: action.payload.alertSubscription,
                id: action.payload.alertSubscription.uniqueID
            }, {
                ...state,
                isLoading: false,
                error: null
            });
export class MyClass {

    constructor(public key1?: string, public key2?: string) { } 
}

我希望它简单地替换集合中的值,而不是试图通过内部调用“Object.assign()”来进行不良更新。或者,以某种方式将对象中的键设置为 null 将是有益的。

标签: typescriptngrxngrx-entity

解决方案


setOne is the way to go.

setOne(payload, state);

Here is full documentation.

addOne: Add one entity to the collection
addMany: Add multiple entities to the collection
setAll: Replace current collection with provided collection
setOne: Add or Replace one entity in the collection
removeOne: Remove one entity from the collection
removeMany: Remove multiple entities from the collection, by id or by predicate
removeAll: Clear entity collection
updateOne: Update one entity in the collection. Supports partial updates.
updateMany: Update multiple entities in the collection. Supports partial updates.
upsertOne: Add or Update one entity in the collection. Supports partial updates.
upsertMany: Add or Update multiple entities in the collection. Supports partial updates.
map: Update multiple entities in the collection by defining a map function, similar to Array.map

推荐阅读