本篇要做什么
本文将在上一篇基础上增加ngrx/store-devtools和actions
github代码:https://github.com/shyandsy/angular-9-ngrx-user-mamagement
上一篇已经安装依赖
npm install @ngrx/store @ngrx/effects @ngrx/entity @ngrx/store-devtools @ngrx/router-store
原教程视频连接
步骤
- 浏览器安装redux devtools插件,我使用chrome浏览器
- 修改src\app\app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { StoreModule } from '@ngrx/store';
//加入这行,引用StoreDevtoolsModule
import { StoreDevtoolsModule } from '@ngrx/store-devtools';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { NavbarComponent } from './navbar/navbar.component';
@NgModule({
declarations: [
AppComponent,
HomeComponent,
NavbarComponent,
],
imports: [
BrowserModule,
StoreModule.forRoot({}),
// 使用StoreDevtoolsModule
StoreDevtoolsModule.instrument(),
AppRoutingModule,
],
providers: [],
bootstrap: [AppComponent],
})
export class AppModule { }
- 现在我们刷新浏览器,打开chrome console的redux面板,可以看到所有的状态变动,方便调试
- 创建actions,src\app\users\state\user.actions.ts
import { Action } from '@ngrx/store';
import { User } from '../user.model';
export enum UserActionTypes {
LOAD_USERS = "[User] Load Users",
LOAD_USERS_SUCESS = "[User] Load Users Success",
LOAD_USERS_FAILED = "[User] Load Users Failed",
}
export class LoadUsers implements Action{
readonly type = UserActionTypes.LOAD_USERS;
}
export class LoadUsersSuccess implements Action{
readonly type = UserActionTypes.LOAD_USERS_SUCESS;
constructor(public payload: User[]) {}
}
export class LoadUsersFailed implements Action{
readonly type = UserActionTypes.LOAD_USERS_FAILED;
constructor(public payload: string) {}
}
export type ACTION = LoadUsers | LoadUsersSuccess | LoadUsersFailed;
- 创建src\app\state\app-state.ts
export interface AppState{
}
- 重写我们的reducer,不提供初始数据
import * as userAction from './user.actions';
import * as fromRoot from '../../state/app-state';
import { User } from '../user.model';
export interface UserState{
users: User[],
loading: boolean,
loaded: boolean,
error: string,
}
export interface AppState extends fromRoot.AppState{
users: UserState;
}
export const initialState: UserState= {
users: [],
loading: false,
loaded: true,
error: "",
}
export function userReducer(state = initialState, action: userAction.ACTION): UserState{
switch(action.type){
case userAction.UserActionTypes.LOAD_USERS:{
return {
...state,
loading: true,
}
}
case userAction.UserActionTypes.LOAD_USERS_SUCESS:{
return {
...state,
loading: false,
loaded: true,
users: action.payload
}
}
case userAction.UserActionTypes.LOAD_USERS_FAILED:{
return {
...state,
loading: true,
loaded: false,
error: action.payload
}
}
default: {
return state;
}
}
}