Using @angular-redux/store
import { Action } from 'redux';
import { CounterActions } from './actions'
export interface AppState {
counter: number;
};
export const INITIAL_STATE: AppState = {
counter: 0,
};
export function rootReducer(state: AppState, action : Action) : AppState {
switch(action.type) {
case CounterActions.INCREMENT: return {counter:state.counter+1};
case CounterActions.DECREMENT: return {counter:state.counter-1};
default : return state;
}
}
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import {NgReduxModule, NgRedux, DevToolsExtension } from '@angular-redux/store';
import { AppState, INITIAL_STATE, rootReducer } from './store';
import { CounterActions } from './actions';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
NgReduxModule
],
providers: [CounterActions],
bootstrap: [AppComponent]
})
export class AppModule {
constructor(ngRedux : NgRedux<AppState>) {
ngRedux.configureStore(rootReducer, INITIAL_STATE);
}
}
import { Component } from '@angular/core';
import {Observable} from 'rxjs/Observable';
import {NgRedux, select} from '@angular-redux/store';
import {CounterActions} from './actions';
import {AppState} from './store';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
@select('counter') readonly count$: Observable<number>;
constructor(private ngRedux : NgRedux<AppState>, private actions: CounterActions) {}
increment() : boolean {
console.log("incrementing");
this.ngRedux.dispatch(this.actions.increment());
return false;
}
decrement() : boolean {
console.log("decrementing");
this.ngRedux.dispatch(this.actions.decrement());
return false;
}
}
import { Injectable } from '@angular/core';
import { NgRedux } from '@angular-redux/store';
import { Action } from 'redux';
import { AppState } from './store';
@Injectable()
export class CounterActions {
static INCREMENT = 'INCREMENT';
static DECREMENT = 'DECREMENT';
increment(): Action {
return {type:CounterActions.INCREMENT};
}
decrement(): Action {
return {type:CounterActions.DECREMENT};
}
}