The ability to reply to discussions is limited to PRO members. Want to join in the discussion? Click here to subscribe now.

Use ngrx/store and Reducers for Angular Application State

Use ngrx/store and Reducers for Angular Application State

5:12
ngrx/store is a library that simplifies common RxJS patterns for managing state and gives you an easy api to use it within your Angular application. This lesson shows how to convert a common startWith and scan stream into an ngrx Store and reducer.
Watch this lesson now
Avatar
egghead.io

ngrx/store is a library that simplifies common RxJS patterns for managing state and gives you an easy api to use it within your Angular 2 application. This lesson shows how to convert a common startWith and scan stream into an ngrx Store and reducer.

Avatar
Oleksii Filippov

I think lesson #7 is outdated. It is not possible to create store:Store variable in the constructor. There is an compile error: Generic type 'Store requires 1 type arguments. Make store:Store instead

In reply to egghead.io
Avatar
Nathan Brenner

This works, and it matches the current docs:

import { StoreModule } from '@ngrx/store';
@NgModule({
    imports: [ StoreModule.provideStore({ clock: clock }, { clock: new Date() })

The first parameter to the provideStore method is the reducer function, the second is the initialized state.

Avatar
Doug

I'm still getting an error in ng2:

ERROR in [default] /Users/dougboyd/look/learn-rxjs/src/app/app.component.ts:21:21 
Generic type 'Store<T>' requires 1 type argument(s).
Child html-webpack-plugin for "index.html":
In reply to Nathan Brenner
Avatar
Jon

I am too. Seems to be a recurring pattern with these courses..Angular2/RxJs is changing too quickly for EggHead to keep up.

In reply to Doug
Avatar
James

It looks like you have to install ngrx separately

step 1 - install from here https://github.com/ngrx/store

npm install @ngrx/core @ngrx/store --save

step 2 - add to your module

import { clock } from './reducers'
import { StoreModule } from 'ngrx/store'

@Ngmodule({
  imports: [ // NOT bootstrap like in the demo
    StoreModule.provideStore({ clock })
 // ... the rest of your module

step 3 - add to your component

import { Store } from '@ngrx/store'

export class AppComponent {
  click$ = new Subject()
  clock
  constructor(store: Store<any>) { // either use `any` type or swap in your class interface for typescript
    this.clock = store.select('clock')
// ...

step 4 - add your .reducers.ts

export const clock = (state: Date = new Date(), {type}) => {
  const date = new Date(state.getTime());
  switch (type) {
    case 'second':
      date.setSeconds(date.getSeconds() + 1);
      return date;
    case 'hour':
      date.setHours(date.getHours() + 1);
      return date;
  }
  return state;
}

Hope this helps!

In reply to Jon
HEY, QUICK QUESTION!
Joel's Head
Why are we asking?