配置应用以使用Redux

Once you have the reducers and actions created, it is time to configure your Angular 2 application to make use of Ng2-Redux. For this, we will need to:

  • Register Ng2-Redux with Angular 2
  • Create our application reducer
  • Create and configure a store

Registering Ng2-Redux with Angular 2

app/index.ts

  1. import { NgModule } from '@angular/core';
  2. import { BrowserModule } from '@angular/platform-browser';
  3. import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
  4. import { NgReduxModule, NgRedux } from 'ng2-redux';
  5. import { SimpleRedux } from './containers/app-container';
  6. @NgModule({
  7. imports: [
  8. BrowserModule,
  9. NgReduxModule
  10. ],
  11. declarations: [
  12. SimpleRedux
  13. ],
  14. bootstrap: [ SimpleRedux ]
  15. })
  16. class AppModule {
  17. }
  18. platformBrowserDynamic().bootstrapModule(AppModule);

Here, we’re simply adding the NgReduxModule class as an import in our NgModule declaration.

Create our Application Reducer

app/reducers/index.ts

  1. import { combineReducers } from 'redux';
  2. import counter from './counter-reducer';
  3. export default combineReducers({
  4. counter
  5. });

combineReducers allows us to break out our application into smaller reducers with a single area of concern. Each reducer that you pass into it will control a property on the state. So when we are subscribing to our state changes with Ng2-Redux’s @select decorator, we are able to select a counter property, or any other reducers you have provided.

Create and Configure a Store

Next we want Ng2-Redux to configure our store based on settings we provide. This should be done once, in the top-level component of your application.

app/containers/app-container.ts

  1. import { Component } from '@angular/core';
  2. import { NgRedux } from 'ng2-redux';
  3. import logger from '../store/configure-logger';
  4. import reducer from '../reducers';
  5. @Component({
  6. // ...
  7. })
  8. class SimpleRedux {
  9. constructor(ngRedux: NgRedux) {
  10. const initialState = {};
  11. const middleware = [ logger ];
  12. ngRedux.configureStore(reducer, initialState, middleware);
  13. }
  14. }

In this example we are creating a store that uses the redux-logger middleware, which will add some logging functionality to the application.