Search code examples
angularngrx

ngrx simple state reducer


New to angular and ngrx, following the docs,

I modified the basic example to the following,

Actions

export const increment = createAction('[Counter Component] Increment');
export const decrement = createAction('[Counter Component] Decrement');
export const reset = createAction('[Counter Component] Reset');

Reducer


export const initialState = {
  num: 0
};

const _counterReducer = createReducer(initialState,
  on(increment, state => ({ num: state.num + 1})),
  on(decrement, state => ({ num: state.num - 1})),
  on(reset, state => ({ num: 0 })),
);

Module

StoreModule.forRoot({ count: counterReducer })

Component

TS

count$: Observable<IState>;

constructor(private store: Store<{ count: IState }>) {
    this.count$ = store.pipe(select('count'));
}

HTML

<p> count$.num | async </p>

Model.ts

export interface IState {
  num: number
}

Seems like I'm missing something trivial.

StackBlitz: https://stackblitz.com/edit/angular-72vhrz


Solution

  • <p> (count$| async).name </p>
    

    You first must use the async pipe on the observably, this will unwrap its value and you can access it.