在 NgRx 实体中更新字典

时间:2021-02-25 13:04:59

标签: angular typescript ngrx ngrx-entity

我正在尝试更新或将新值插入到 ngrx 实体下的字典中。

这是实体的简化视图:

interface Dictionary<T> { [key: number]: T }

export class Item {
  id: number;
  partsDescriptions: Dictionary<string[]>;
}

export interface ItemsState extends EntityState<Item> {
}

这是应用状态:

export interface AppState {
  items: ItemsState
}

在减速器中,我尝试执行以下操作:

on(MyActions.partDescriptionsLoaded, (state, action) => {
    return {
      ...state,
      items: adapter.updateOne({
        id: action.id,
        changes: {
          ...state.items[action.id],
          partsDescriptions: {
            ...(state.items[action.id] && state.items[action.id].partsDescriptions),
            [action.partId]: action.partDescriptions
          }
        }
      }, state.items)
    }
  })

PartDescriptions 字典没有扩展,它总是被替换。你知道如何解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

作为一般答案:
给定一个处于状态的对象,例如 descriptions,为了更新它而不是替换它,您将执行以下操作:

descriptions: {
    ...state.descriptions,
    newDescriptions,
}


至于您的代码,请尝试执行以下操作:

partsDescriptions: {
    ...state.partsDescription,
    elementsYouWantToExtendThisObjectWith,
}