Angular : Adding store + reducer
Added reducer or store pretty much the same thing, to me. To setup the required libraries,
npm install @ngrx/store --save
First you need some sort of actions
import { Action } from '@ngrx/store';
export enum ActionTypes {
Login = 'Login',
Logout = 'Logout',
Reset = 'Reset',
}
export class Login implements Action {
readonly type = ActionTypes.Login;
}
export class Logout implements Action {
readonly type = ActionTypes.Logout;
}
export class Reset implements Action {
readonly type = ActionTypes.Reset;
}
export type ActionsUnion = Login | Logout | Reset;
Then you setup your reducer :-
import {
ActionReducer,
ActionReducerMap,
createFeatureSelector,
createSelector,
MetaReducer
} from '@ngrx/store';
import { environment } from '../../environments/environment';
import { ActionsUnion, ActionTypes, Login } from '../actions/Login';
import { Action } from '@ngrx/store';
export interface State {
type : string,
actionValue : number;
}
export const initialState: State = {
type: "empty",
actionValue : 0,
};
export function LoginReducer(state = initialState, action: Login): State {
console.log("store reducer happening...")
switch (action.type) {
case ActionTypes.Login:
console.log("login reducer");
return {
...state,
type : state.type,
actionValue : state.actionValue,
};
defaut:
return initialState;
}
}
In the app.module.ts, we setup our store and tied to our reducer. Please note that we specify {
login : LoginReducer,
}
import { StoreModule } from '@ngrx/store';
@NgModule({
declarations: [
AppComponent,
CarInsuranceComponent,
HouseInsuranceComponent,
HealthInsuranceComponent,
],
imports: [
BrowserModule,FormsModule,AppRoutingModule,
StoreModule.forRoot({login : LoginReducer}),
EffectsModule.forRoot([AppEffects])
],
providers: [],
bootstrap: [AppComponent]
})
Comments