初涉angular之Ngxs状态管理

ngxs是一款angular的状态管理框架。他能帮助我们全局性的管理应用程序的所有状态,状态的概念无所不包,我们的数据,登录认证,等等,都可以称为状态。

ngxs架构

ngxs有四个概念:

  • Store: Global state container, action dispatcher and selector
  • Actions: Class describing the action to take and its associated metadata
  • State: Class definition of the state
  • Selects: State slice selectors

store是ngxs核心,action,selects最终将融入state类,并被注册到store里
请看下图:


安装npm

npm install @ngxs/store --save
npm install @ngxs/devtools-plugin --save
npm install @ngxs/logger-plugin --save
// app.module.ts
import { NgxsModule } from '@ngxs/store';
import { NgxsReduxDevtoolsPluginModule} from '@ngxs/devtools-plugin';
import { NgxsLoggerPluginModule } from '@ngxs/logger-plugin';
@NgModule({
 imports: [
    BrowserModule,
    FormsModule,
    AppRoutingModule,
    HttpClientModule,
    NgxsModule.forRoot([
      UserState
    ]),
    NgxsReduxDevtoolsPluginModule.forRoot(),
    NgxsLoggerPluginModule.forRoot()
  ], 
...
})

官网地址:https://ngxs.gitbook.io/ngxs/

项目目录结构
store目录
action类
export class Edit {
  static readonly type = '[user] Edit';
  constructor(public payload: { userEdit: any }) {}
}
model类
export class User {
  userId: string;
  username: string;
  password: string;
}

state类
import {State, Action, Selector, StateContext} from '@ngxs/store';
import { Router } from '@angular/router';
import { NgZone } from '@angular/core';
import { Response, ResponseCode } from '../models/response.model';
import {map} from 'rxjs/operators';
import * as UserAction from '../actions/user.action';
import { User } from '../models/user.model';
import { UserService } from '../services/user.service';

export class UserStateModel {
  userInfo: User;
}

@State<UserStateModel>({
  name: 'user',
  defaults: {
    userInfo: null
  }
})

export class UserState {
  @Selector()
  static getLoginUser(state: UserStateModel) {
    return state.userInfo;
  }
  constructor(
    private router: Router,
    public ngZone: NgZone,
    private userService: UserService) {}

    @Action(UserAction.Edit)
    Edit(ctx: StateContext<UserStateModel>, action: UserAction.Edit) {
      console.log(action.payload.userEdit);
      ctx.patchState({
        userInfo : action.payload.userEdit
      });
    }
}

Component View显示 主要代码
export class HomeComponent implements OnInit {
  userInfo: any;
// 1.在component中订阅userInfo状态
  @Select(UserState.getLoginUser) userInfo$: Observable<User>;

  ngOnInit() {
// 2.subscribe订阅
    this.userInfo$.subscribe(userInfo => {
      this.userInfo = userInfo;
    });
  }
updateName() {
    this.userInfo.username = this.nameUpdate;
// 3.在component中使用dispatch
    this.store.dispatch(new Edit({
      userEdit: this.userInfo,
    }));
  }
}
<p class="home-message">恭喜{{(userInfo$ | async).username}}登录成功!</p>
<p class="home-message">{{userInfo.username}},你好!</p>
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容