无法在使用 ngRx 的反例中看到计数值

Unable to see count value in counter example using 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$ 发生变化,尽管正在调用 reducer 并且状态正在发生变化。作为我的第一个 ngRx 项目,我知道在观察 Store.

时我遗漏了一个非常小的概念

有人可以帮忙吗?

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

当您订阅时,请记住这将 return 一个 AppState 类型的对象,如下所示:

{ count: 0 };

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

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

这将在对象被解包后读取。我们添加 ? 以确保在 observable 展开之前我们不会收到任何错误