Fork Me On Github

angular 11 ngrx/store 使用理解

声明

export interface AuthSate {
    site: ISite;
    cart: any;
}

export const authFeatureKey = 'auth';

export interface AppState {
    [authFeatureKey]: AuthSate;
}

export const initialState: AuthSate = {
    site: null, // 初始化时,必须设置值,未设置(undefined)的将无法通知
    cart: null,
};

// 定义根据action 修改方法
const authReducer = createReducer(
    initialState,
    on(setCart, (state, {cart}) => ({...state, cart})),
    on(setSite, (state, {site}) => ({...state, site})),

    on(clearAuth, state => Object.assign({}, initialState)), // 返回初始化
);

export function reducer(state: State<AppState> | undefined, action: Action) {
    return authReducer(state, action);
}

Actions

定义action 用于修改Store中的数据

export const setCart = createAction('[shop]SET_CART', props<{cart: ICart}>());
export const setSite = createAction('[shop]SET_SITE', props<{site: ISite}>());

相当于

export const setCart = (cart: ICart) => ({
    type: '[shop]SET_CART',
    payload: {cart},
});

Selectors

定义 selector 用于获取数据

export const selectAuth = createFeatureSelector<AppState, AuthState>(authFeatureKey);

export const selectCart = createSelector(
    selectAuth,
    (state: AuthState) => state.cart
);

export const selectSite = createSelector(
    selectShop,
    (state: AuthState) => state.site
);

注册到程序中

注册根

app.module.ts

StoreModule.forRoot({
    [authFeatureKey]: reducer,
}),

这是必须的如果没有全局数据,则

StoreModule.forRoot({}),

也可以为某一个模块注册局部数据

StoreModule.forFeature(authFeatureKey, reducer),

使用

  1. 设置
export class AppComponent {
    constructor(
        private store: Store<AppState>,
    ) {

    }

    setSite() {
        this.store.dispatch(setSite({site: {}}));
    }
}
  1. 获取数据
export class AppComponent {
    constructor(
        private store: Store<AppState>,
    ) {
        this.store.select(selectSite).subscribe(site => {
            // TODO
        });
    }
}
Click here to view
Tags: angular
0 481 0
使用ng-template 显示tree结构数据
使用 ViewContainerRef.createComponent 替代 ComponentFactoryResolver
angular 12使用 KaTex 显示 AsciiMath 格式的公式
ng-deep 使用
angular 12 动态生成组件