Samuel
Samuel

Reputation: 1416

Unable to see count value in counter example using ngRx

Here is the code:

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());
  }
}

I am not able to see counter$ getting changed, although the reducers are getting called and the state getting changed. As my 1st ngRx project I know I am missing a very small concept while observing the Store.

can someone please help ?

Upvotes: 2

Views: 1544

Answers (1)

user184994
user184994

Reputation: 18281

I think you need to change StoreModule.forRoot({counterReducer}) to StoreModule.forRoot({count: counterReducer})

When you subscribe, bear in mind that this will return an object of type AppState like below:

{ count: 0 };

So when you're using async pipe, change it to:

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

This will read from the object once it's been unwrapped. We add the ? to ensure that we don't get any errors before the observable has been unwrapped

Upvotes: 2

Related Questions