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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With