如何从Reducer Ngrx

时间:2018-02-03 01:07:58

标签: redux ngrx

我有以下减速机

import { EntityState, createEntityAdapter } from '@ngrx/entity';
import { createFeatureSelector } from '@ngrx/store';

export const pageAdapter = createEntityAdapter<Page>({
  //selectId: (collection: Collection) => collection.id,
});

export interface State extends EntityState<Page> {
}

const defaultPage = {
    ids: ['kHnryus'],
    entities: {
        'kHnryus': {
        id: '83nryus',
        title: 'How to create a blog with Angular4 Ngrx',
        description: 'How to create a blog with Angular4 Ngrx',
    }
  },
  success_create: false
}

export const initialState: State = pageAdapter.getInitialState();

// Reducer
export function pageReducer(
    state: State = initialState,
    action: actions.PageActions) {

    switch (action.type) {
        case actions.ADD_ALL: {
            return pageAdapter.addAll(action.pages, state);
          };
        case actions.SUCCESS: {
            return {success_create: true}
        };
        default:
            return state;
        }

}

// Create the default selectors
export const getPageState = createFeatureSelector<State>('page');

export const {
    selectIds,
    selectEntities,
    selectAll,
    selectTotal,
  } = pageAdapter.getSelectors(getPageState);

我想得到组件中状态的布尔变量success_create

基本上,我希望如果有SUCCESS,我应该能够在组件类中获得success_create true。我不知道如何做到这一点,即使它是可能的。

如果是,请问我该如何实现?

1 个答案:

答案 0 :(得分:1)

首先确保删除server常量,因为您没有在reducers中维护它,并且您已经使用@ngrx/entitydefaultPage应定义如下:

success_create

然后,在您的默认选择器之后添加使用export interface State extends EntityState<Page> { success_create: boolean; } export const adapter: EntityAdapter<Item> = createEntityAdapter<Page>({ selectId: (page: Page) => page.id, sortComparer: false }); export const initialState: State = adapter.getInitialState({ success_create: false, }); 选择器的第三个选择器并向您的状态深入一步:

getPageState

然后让您的组件/服务直接听取它:

export const getSuccessCreate = createSelector(
  getPageState, 
  (state: State) => state.success_create
);

注意:此处的管道是可选的,如果使用,则this.created$ = this.store.pipe(select(fromPages.getSuccessCreate)); 应该select导入@ngrx/store,因为它已完成in the official ngrx demo app。 pipe允许您使用lettable rxjs运算符。您可以阅读更多相关信息here