首页 > 解决方案 > action start 和 store 更新时如何拦截?

问题描述

我正在使用 NGRX。我有很多操作,我想知道操作何时开始以及商店何时更新。

这个想法是无论执行什么操作,都有一个集中的方式来获取信息。我需要知道商店何时更新而不订阅所有选择器。

updateTitle ----> 标题已更新。

最好的,赫门德斯

标签: ngrxngrx-effectsngrx-entity

解决方案


您必须明确定义操作

例如

import { createAction, props } from "@ngrx/store";    

export enum HeaderActionTypes {
  UpdateTitle = '[Title] Update Title',
  UpdateTitleSuccess = '[Title] Update Title success'
}

export const UpdateTitle = createAction(HeaderActionTypes.UpdateTitle)
export const UpdateTitleSuccess = createAction(HeaderActionTypes.UpdateTitleSuccess, props<{ payload: string }>())

在 reducer 中,您可以捕获动作并更新状态

例如

import { createReducer, on } from "@ngrx/store";

export const initialState = {
   ... // Additional state properties can go here. 
   updatingTitle: false,
   title: ''
}


export const reducer = createReducer(
  initialState,
  on(HeaderActionTypes.UpdateTitle, (state) => {
    return {
      ...state,
      updatingTitle: true
   }
  }),
  on(HeaderActionTypes.UpdateTitleSuccess, (state, { payload }) => {
    return {
      ...state,
      updatingTitle: false,
      title: payload
   }
  })
)

如果title通过async电话更新,您必须添加一个Effect

效果,查看文档。

Selectors,使用选择器读取状态并将其绑定到 UI。


推荐阅读