Define the actions and reducer for loading
Create the States folder in the project and create the Action and Reducer files under it. Simulate a user logging in to a state manager that stores user information
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;
Copy the code
userReducer
import * as userActions from '.. /actions/user.action';
export interfaceState { 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:
returnstate; }}Copy the code
User Data Template
import { IRouterStates } from './router.store'; import {State} for '.. /reducer/userReducer' export interface AppStore { user: State; }Copy the code
Introduced in app.module.ts
@NgModule({
declarations: [AppComponent],
imports: [
StoreModule.forRoot({ user: userReducer })
]
})
Copy the code
Update the appName in the Store with action
this.store.dispatch(new UserLogin( userinfo));
this.store.dispatch(new UserLogOut());
Copy the code
Get userInfo data
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);
});
}
Copy the code