RxJS powered Redux for Angular2 apps
- Make sure you have angular2 installed via npm :
npm install angular - Install from npm :
npm install @ngrx/store
- Create a reducer function for each data type you have:
//counter.tsimport{Reducer,Action}from'@ngrx/store';exportconstINCREMENT='INCREMENT';exportconstDECREMENT='DECREMENT';exportconstRESET='RESET';exportconstcounter:Reducer<number>=(state:number=0,action:Action)=>{switch(action.type){caseINCREMENT:
returnstate+1;break;caseDECREMENT:
returnstate-1;break;caseRESET:
return0;break;default:
returnstate;break;}}- In your app's main module, import those reducers and use the
provideStore(reducers, initialState)function to provide them to Angular's injector:
import{bootstrap}from'angular2/platform/bootstrap';import{provideStore}from'@ngrx/store';import{App}from'./myapp';import{counter}from'./counter';bootstrap(App,[provideStore({counter},{counter: 0})];- You can then inject the
Storeservice into your Components and Services:
import{Store}from'@ngrx/store';import{INCREMENT,DECREMENT,RESET}from'./counter';
@Component({selector: 'my-app',template: ` <button (click)="increment()">Increment</button> <div>Current Count: {{ counter | async }}</div> <button (click)="decrement()">Decrement</button> `})classMyApp{counter: Observable<number>;constructor(publicstore: Store){this.counter=store.select('counter');}increment(){this.store.dispatch({action: INCREMENT});}decrement(){this.store.dispatch({action: INCREMENT});}}