Store

Store is observable object that holds all application state

Store can be accessed in one of 2 ways:

  • From Actions

  • Injected directly into component via DI

@Component({
  selector: 'my-app',
  template: `
    <div>todos: {{ (todos | async)?.getIn([0]) }}</div>
  `
})
class MyAppComponent {
  todos: Observable<number>;

  constructor(private store: Store<AppState>){
    this.todos = store.select(['todos']);
  }
}

Also you can avoid having async pipe by subscribing to state change. But then you will be responsible for subscription management and view update when OnPush change detection is applied. Hence it is recommended to leave this for Angular.

@Component({
  selector: 'my-app',
  template: `
    <div>todos: {{ todos.getIn([0]) }}</div>
  `
})
class MyAppComponent {
  todos: Map<any, any>;
  subscription: Rx.Subscription;

  constructor(private store: Store<AppState>, cd: ChangeDetectorRef) implements OnDestroy {
    this.subscription = store.select(['todos'])
      .subscribe(state => {
        this.todos = state; // OR this.todos = state.toJS()
        cd.markForCheck();
      });
  }

  ngOnDestroy(){
    this.subscription.unsubscribe();
  }
}

TIP: try to avoid .toJS() calls because it is not the best practice and is might be costly performance vise.

Last updated