在Angular 2应用程序中使用@ ngrx / store

时间:2016-11-07 10:50:49

标签: angular ngrx

我试图实现here中提到的示例来理解 @ ngrx / store的基础知识。

以下是我实施的代码

Reducer" counter.cs"代码

import { Action , ActionReducer } from '@ngrx/store';

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


 export const counterReducer: ActionReducer<number> = (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;    
     }

   }

功能模块代码//rx.module.ts

import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { StoreModule } from '@ngrx/store';

import { CommonModule } from '@angular/common';
import { counterReducer } from './counter';
import { StoreComponent } from './store.component';

@NgModule({
   imports: [
              RouterModule.forChild([   
             {path:'store' , component: StoreComponent}
             ]),
             StoreModule.provideStore({counter: counterReducer}),
             CommonModule
            ],
   providers: [],
   exports:[],
   declarations:[StoreComponent]
})

export class RxModule { }

这是组件代码

// component code store.component.ts

import { Store } from '@ngrx/store';
import { Component } from '@angular/core';
import { Observable } from 'rxjs/Observable';

import { INCREMENT , DECREMENT , RESET } from './counter';

 interface AppState {
counter: number;
 }

 @Component({
 selector:'',
 template: `
 <h2> ngrx/store Example </h2>

  Current state : {{counter | async }}
  <input type="button" (click)="increment()" value="Increment"><br>
  <input type="button" (click)="decerment()" value="Decrement">

   `
 })

 export class StoreComponent {

  counter: Observable<number>;

  constructor(private store: Store<AppState>) {
     this.counter = this.store.select('counter');
  }

   increment() {
  this.counter = this.store.dispatch({ type: INCREMENT });
   }

   decerment() {
  this.counter = this.store.dispatch({type: DECREMENT});
   }
  }

编译此代码会给我以下错误

  

输入&#39; Observable&lt; {}&gt;&#39;不能分配给&#39; Observable&#39;。     输入&#39; {}&#39;不能分配类型&#39;数字&#39;。

并且此错误指向store.component.ts

中的下面一行代码
this.counter = this.store.select('counter');

任何想法是什么问题。

0 个答案:

没有答案