首页 > 解决方案 > 无法从商店 ngrx 获取值

问题描述

我面对的是 NgRx,我不明白怎么会这么难为商店添加价值并检索它。无论如何,这就是我到目前为止所做的

效果ts:

export class idEffects {

    saveId$ = createEffect(() =>
    this.actions$
        .pipe(
            ofType(idActions.addIdAction),
            tap(payload => {
                console.log("action",payload);
            })
        )
    ,{dispatch: false});

    constructor(
      private actions$: Actions
    ) {}
  }

行动 ts:

export const ADD_ID = '[Id Action] 添加 id';

export const addIdAction = createAction(
    ADD_ID,
    props<{id: any}>()
)

减速机 ts:

export interface IdState {
    id: any;
}

export const defaultId: IdState = {
    id: undefined
};

export const idReducer = createReducer (
    defaultId,

    on(idActions.addIdAction, (state, action) => {
        //console.log("Calling id reducer", action);
        return {
            id: action
        }
    })
)

和选择器ts:

export const selectIdState = 
createFeatureSelector<IdState>("id")

export const selectIdValue = createSelector(
    selectIdState,
    id => id
);

现在,这就是我的 app.module.ts 中的内容

StoreModule.forRoot({id: idReducer}),
    EffectsModule.forRoot([IdEffects]),
    StoreModule.forRoot(reducers, {
      metaReducers
    }),
    StoreDevtoolsModule.instrument({maxAge: 25}),
    StoreRouterConnectingModule.forRoot({
      stateKey: 'router',
      routerState: RouterState.Minimal
    })

似乎存储数据运行良好,因为我控制台中的 Redux 面板返回以下内容:

id(pin):"1"
data(pin):"Hello There"
type(pin):"[Id Action] add id"

但是,当我尝试检索这个对象时,我得到一个undefined并且我这样做:

this.id$ = storeId.pipe(select(selectIdValue))

并在 html

<h4>The id obj is: {{id$ | async}}</h4>

但它什么也没写。我试图在组件中使用订阅来获得结果,它让我undefined怎么可能?

标签: angulartypescriptngrxngrx-store

解决方案


国家是

export interface IdState {
    id: any;
}

因此选择器应该从其特征状态中选择 id

export const selectIdValue = createSelector(
    selectIdState,
    state => state.id, // selectIdState returns an object of IdState interface.
);

然后,reducer,它应该将idprop 添加到 state,而不是action

    on(idActions.addIdAction, (state, action) => {
        //console.log("Calling id reducer", action);
        return {
            ...state, // not needed in your case, but a good style.
            id: action.id, // <- .id
        }
    }),

效果,它不是必需的,您可以将其删除。

最后一件事是reducers变量。你能分享它的来源吗?它应该是

const reducers = {
  id: idReducer, // id key is important, idReducer is enough for now.
};

别忘了派人去某个地方addIdAction。例如在ngOnInit一个组件中。

this.store.dispatch(addIdAction({id: 'value'}));

如果你有这样的事情 - 它应该工作。如果您有更多问题,请告诉我。


推荐阅读