Angular使用ngrx管理状态

297 阅读1分钟

定义loading的action和reducer

在项目中创建states文件夹,并在之下创建action和reducer文件。模拟一个用户登录储存用户信息的状态管理器

userActions

export const types = {
    USER_LOGIN: "USER_LOGIN",
    USER_LOGOUT: "USER_LOGOUT"
}
export class UserLogin implements Action {
    readonly type = types.USER_LOGIN;
    constructor(public payload:string){}
}
export class UserLogOut implements Action {
    readonly type = types.USER_LOGOUT;
}
export type Actions = UserLogin|UserLogOut;

userReducer

import * as userActions from '../actions/user.action';

export interface State {
  username?: string;
  token?: string;
  otherData: any
}

export const initialState: State = {};

export function userReducer(state = initialState, action: userActions.ActionUnion): State {
  switch (action.type) {
    case userActions.ActionTypes.UserLogin:
     return action.payload||state;

    case userActions.ActionTypes.UserLogOut:
      return {};

    default:
      return state;
  }
}

user数据模板

import { IRouterStates } from './router.store';
import {State} for '../reducer/userReducer'
export interface AppStore {
  user: State;
}

在app.module.ts中引入

@NgModule({
  declarations: [AppComponent],
  imports: [
    StoreModule.forRoot({ user: userReducer })
  ]
})

通过action更新store中的appName

 this.store.dispatch(new UserLogin( userinfo));
 this.store.dispatch(new UserLogOut());

获取userinfo数据

export class CompleteComponent implements OnInit, OnDestroy {
  constructor(private store: Store<AppStore>) {
    this.userState$ = store.select('user');
  }
  ngOnInit() {
    this.tagStateSubscription = this.userState$.subscribe((state) => {
    	console.log(state);
    });
  }