angular 9打造用户系统 - 5使用ngrx entity

楚天乐 57 0 条

本篇要做什么

本文将使用effect entity库来管理数据集,减少CRUD操作代码量,通过id来查找user

github代码:https://github.com/shyandsy/angular-9-ngrx-user-mamagement

安装ngrx entity

npm install @ngrx/entity

原教程视频连接

步骤

  1. 修改src\app\users\state\user.reducer.ts
import * as userAction from './user.actions';
import {createFeatureSelector, createSelector, Store} from '@ngrx/store';

// 加入
import {EntityState, EntityAdapter, createEntityAdapter } from '@ngrx/entity';

import * as fromRoot from '../../state/app-state';
import { User } from '../user.model';

// 改用EntityState
export interface UserState extends EntityState<User>{
    selectedUserId: number | null;
    loading: boolean,
    loaded: boolean,
    error: string,
}

export interface AppState extends fromRoot.AppState{
    users: UserState;
}

export const userAdapter: EntityAdapter<User> = createEntityAdapter<User>();

export const defaultUser: UserState = {
    ids: [],
    entities: {},
    selectedUserId: null,
    loading: false,
    loaded: false,
    error: ""
}

export const initialState: UserState = userAdapter.getInitialState(defaultUser);

export function userReducer(state = initialState, action: userAction.ACTION): UserState{
    switch(action.type){
        case userAction.UserActionTypes.LOAD_USERS:{
            console.log("reducer: LOAD_USERS")
            return {
                ...state,
                loading: true,
            }
        }
        case userAction.UserActionTypes.LOAD_USERS_SUCESS:{
            console.log("reducer: LOAD_USERS_SUCESS")
            return userAdapter.addAll(action.payload, {
                ...state,
                loading: false,
                loaded: true,
            })
        }
        case userAction.UserActionTypes.LOAD_USERS_FAILED:{
            console.log("reducer: LOAD_USERS_FAILED")
            return {
                ...state,
                entities: {},
                loading: true,
                loaded: false,
                error: action.payload
            }
        }
        default: {
            return state;
        }
    }
}

const getUserFeatureState = createFeatureSelector<UserState>(
    "users"
)

export const getUsers = createSelector(
    getUserFeatureState,
    userAdapter.getSelectors().selectAll
)

export const getUsersLoading = createSelector(
    getUserFeatureState,
    (state: UserState) => state.loading
)

export const getUsersLoaded = createSelector(
    getUserFeatureState,
    (state: UserState) => state.loaded
)

export const getError = createSelector(
    getUserFeatureState,
    (state: UserState) => state.error
)

解释

  1. 引入ng/entity
import {EntityState, EntityAdapter, createEntityAdapter } from '@ngrx/entity';
  1. UserState改为继承EntityState,加入selectedUserId记录当前选中的User Id
// 改用EntityState
export interface UserState extends EntityState<User>{
    selectedUserId: number | null;
    loading: boolean,
    loaded: boolean,
    error: string,
}
  1. 创建userAdapter对象
export const userAdapter: EntityAdapter<User> = createEntityAdapter<User>();
  1. 创建default user对象
export const defaultUser: UserState = {
    ids: [],          // 对象ids
    entities: {},
    selectedUserId: null,
    loading: false,
    loaded: false,
    error: ""
}
  1. 改用userAdapter创建initialState
export const initialState: UserState = userAdapter.getInitialState(defaultUser);
  1. 修改userReducer
export function userReducer(state = initialState, action: userAction.ACTION): UserState{
    switch(action.type){
        case userAction.UserActionTypes.LOAD_USERS:{
            console.log("reducer: LOAD_USERS")
            return {
                ...state,
                loading: true,
            }
        }
        case userAction.UserActionTypes.LOAD_USERS_SUCESS:{
            console.log("reducer: LOAD_USERS_SUCESS")

            // 改用userAdapter的addAll方法
            return userAdapter.addAll(action.payload, {
                ...state,
                loading: false,
                loaded: true,
            })
        }
        case userAction.UserActionTypes.LOAD_USERS_FAILED:{
            console.log("reducer: LOAD_USERS_FAILED")
            return {
                ...state,
                entities: {},
                loading: true,
                loaded: false,
                error: action.payload
            }
        }
        default: {
            return state;
        }
    }
}
  1. 修改getUsers方法,改用userAdapter.getSelector
export const getUsers = createSelector(
    getUserFeatureState,
    userAdapter.getSelectors().selectAll
)

效果

11.png



发表我的评论
昵称 (必填)
邮箱 (必填)
网址