在Angular中实现简单的redux存储计数器实现时出错

时间:2017-08-01 11:32:53

标签: angular ngrx-store

我正在尝试学习如何在角度应用中实现redux。我跟着   https://github.com/ngrx/platform/tree/master/docs/store

我按照提供的所有步骤进行了操作,但收到此错误

  

类型''counter''的参数不能分配给'(state:IAppState)=>类型的参数。数”。

我无法理解我错过了什么。

import { Observable } from 'rxjs/Observable';
import { MileStoneService } from './milestone.service';
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Store } from '@ngrx/store';
import {  INCREMENT ,DECREMENT ,RESET} from './app.actions'; // <- New    
import { MileStoneModel } from "app/MileStoneModel";
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
interface IAppState {
  counter: number;
  //mileStones: MileStoneModel[]
}

export class AppComponent implements OnInit  {
  title = 'app';
  counter$: Observable<number>;
 readonly mileStones$: Observable<MileStoneModel>;

 constructor(private store: Store<IAppState>  , private _service: MileStoneService ) {
     // HERE IS THE ERROR
        this.counter$ = this.store.select<number>('counter');
    }

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

    decrement(){
        this.store.dispatch({ type: DECREMENT });
    }

    reset(){
        this.store.dispatch({ type: RESET });
    }

}

App模块类

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { MileStoneService } from './milestone.service';
import { AppComponent } from './app.component';
import { Http,HttpModule, Response, Headers, RequestOptions } from '@angular/http';


import { StoreModule } from '@ngrx/store';
import { EffectsModule } from '@ngrx/effects';
import { StoreDevtoolsModule } from '@ngrx/store-devtools';
import { environment } from '../environments/environment';
import { counterReducer } from "app/app.actions";

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule  , HttpModule ,
    StoreModule.forRoot({ counter: counterReducer }) ,
    !environment.production ? StoreDevtoolsModule.instrument() : [],

  ],
  providers: [ MileStoneService],
  bootstrap: [AppComponent]
})
export class AppModule { 


}

减速器功能

export const INCREMENT  = '[Counter] Increment';
export const DECREMENT  = '[Counter] Decrement';
export const RESET      = '[Counter] Reset';

export function counterReducer(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;
    }
}

0 个答案:

没有答案