使用ngRx

时间:2018-01-07 10:31:50

标签: angular redux ngrx

以下是代码:

  

state.ts

export interface AppState{
  count : number;
}
  

actions.ts

export const INCREMENT: string = '[Counter] INCREMENT';
export class increment implements Action{
   readonly type = INCREMENT;
}

export const DECREMENT: string = '[Counter] DECREMENT';
export class decrement implements Action{
    readonly type = DECREMENT;
}

export type All
    = increment
    | decrement;
  

reducer.ts

const initState: AppState = { count: 0 };

export function counterReducer(state: AppState = initState, action: Action)         {
  switch (action.type) {
    case INCREMENT:
        return Object.assign({}, state, { count: state.count + 1 });
    case DECREMENT:
        return Object.assign({}, state, { count: state.count - 1 });
    default:
        return state;    
  }
}
  

module.ts

@NgModule({
  declarations: [AppComponent],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    StoreModule.forRoot({counterReducer})
  ],
  providers : [],
  bootstrap: [AppComponent]
})
export class AppModule {}
  

MY-component.ts

export class AppComponent {
  title = 'Welcome to the Redux Counter example';
  counter$ : Observable<number>;
  constructor(public store : Store<AppState>,){
    this.counter$ = this.store.select('count'); // <-- This is not working
  }

  increase(){
    this.store.dispatch(new increment());
  }

  decrease(){
    this.store.dispatch(new decrement());
  }
}

我无法看到counter$被改变,尽管减速器被调用并且状态发生了变化。作为我的第一个ngRx项目,我知道在观察Store时我错过了一个非常小的概念。

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

我认为您需要将StoreModule.forRoot({counterReducer})更改为StoreModule.forRoot({count: counterReducer})

订阅时,请记住这会返回AppState类型的对象,如下所示:

{ count: 0 };

因此,当您使用异步管道时,请将其更改为:

{{ (counter$ | async)?.count }} 

一旦它被解开,这将从对象中读取。我们添加?以确保在观察资料被解开之前我们没有收到任何错误