首页 > 解决方案 > 当 Id 匹配时,角度 ngrx 状态数组项更新

问题描述

我想知道如何在 ngrx 状态数组中添加项目 - 如果不存在 - 或更新 - 如果项目确实存在且匹配 id initialState.calls。下面的例子进行调查。在整个网络中,没有适当的通用示例如何做到这一点。

export interface Call {
  timestamp: number;
  call_id: string;
  tag: Tag[];
}

export default interface KeywordsModel {
  version: string;
  calls: Call[];
  isOpen: boolean;
  lastUpdatedOn: number;
}

 export const initialState: KeywordsModel = {
   calls: [],
   lastUpdatedOn: Date.now()
 };

export const reducer = createReducer(
  initialState,
  on(KeywordsWebSocketActions.messageReceived, (state, { message, timeReceived }) => ({
    ...state,
    ...message,
    lastUpdatedOn: timeReceived
  })),
  on(KeywordsWebSocketActions.keywordsPageOpened, state => ({ ...state, isOpen: true })),

  // Here I need to create action 'messageCallReceived' below doesnt work
  on(KeywordsWebSocketActions.messageCallReceived, (state, { call }) => ({
    ...state, calls: (state.calls.map((existCall: Call) => (existCall.call_id === call.call_id) ? existCall = call : [...state.calls, call])),
  }))
)

标签: angulartypescriptngrxngrx-store

解决方案


您可以将 @ngrx/entity 用于该 Calls 数组,请参见此处https://ngrx.io/guide/entity。然后您可以使用 upsert 操作添加或更新https://ngrx.io/guide/entity/adapter


推荐阅读