ngrx/store - 适合 Angular2 应用的状态管理

1,668 阅读1分钟
原文链接: github.com

Join the chat at https://gitter.im/ngrx/store Codeship Status for ngrx/store npm version

RxJS powered state management inspired by Redux for Angular2 apps

Demo

plnkr.co/edit/Hb4pJP…

installation

  • Make sure you have angular2 installed via npm : npm install angular
  • Install from npm : npm install @ngrx/store

usage

  • Create a reducer function for each data type you have:
//counter.ts
import {Reducer, Action} from '@ngrx/store';

export const INCREMENT = 'INCREMENT';
export const DECREMENT = 'DECREMENT';
export const RESET = 'RESET';

export const counter:Reducer = (state:number = 0, action:Action) => {

    switch (action.type) {
        case INCREMENT:
            return state + 1;

        case DECREMENT:
            return state - 1;

        case RESET:
            return 0;

        default:
            return state;
    }
}
  • 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 Store service into your Components and Services:
import {Store} from '@ngrx/store';
import {INCREMENT, DECREMENT, RESET} from './counter';

@Component({
    selector: 'my-app',
    template: `
      Increment
        
Current Count: {{ counter | async }}
Decrement ` }) class MyApp { counter: Observable; constructor(public store: Store){ this.counter = store.select('counter'); } increment(){ this.store.dispatch({ type: INCREMENT }); } decrement(){ this.store.dispatch({ type: DECREMENT }); } reset(){ this.store.dispatch({ type: RESET }); } }