Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the constructor in order to select on the store and ngOnInit in order to dispatch from the store

My question relates to dispatching & selecting from the ngrx store.

Let's look at the following code from the official example app:

export class CollectionPageComponent implements OnInit {
  books$: Observable<Book[]>;

  constructor(private store: Store<fromBooks.State>) {
    this.books$ = store.select(fromBooks.getBookCollection);
  }

  ngOnInit() {
    this.store.dispatch(new collection.Load());
  }
}

I would like to understand what motivated the choice of dispatching from ngOnInit and selecting from the constructor.

Can anyone please provide an explanation?

P.S. By the way, the above is sample code from the ngrx example app that can be found here: https://github.com/ngrx/platform/blob/master/example-app/app/books/containers/collection-page.ts

like image 615
balteo Avatar asked Oct 29 '17 17:10

balteo


1 Answers

The constructor is executed when the class is instantiated and ensures proper initialization of the class´ fields. This is where Angular resolves providers you may pass as arguments in your constructor.

The ngOnInit lifecycle hook is called after the data-bound properties have been checked for the first time (inputs & outputs of the component). For a more detailed explanation see this question.

The motivation for selecting from ngrx store in the constructor and dispatching from ngOnInit as far as I understand it, is that selecting is part of initializing you component class. Since this.books$ is an Observable, it makes sense initialize it in the constructor so it is ready for use immediately after creation. Assuming the bookCollection.Load() emits a value to this.books$ you want this.books$ to be an observable of those books before an eventual value is emitted.

Since you want those values emitted to this.books$ it makes sense to dispatch the action in ngOnInit. This way you can ne certain that this.books$ is initialized.

This answer to a similar question might also be of help.

like image 151
amu Avatar answered Oct 20 '22 05:10

amu