Using the constructor to select from the store and ngOnInit to send from the store

My question is about dispatching and choosing from the ngrx store.

Take a look at the following code from the official sample application:

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 sending from ngOnInit and choosing from constructor .

Can anyone clarify?

PS By the way, the above code example from the ngrx application example, which can be found here: https://github.com/ngrx/platform/blob/master/example-app/app/books/containers/collection-page.ts

+7
ngrx ngrx-store
source share
2 answers

The constructor runs when the class is instantiated and ensures that the class fields are correctly initialized. Here Angular resolves providers, which you can pass as arguments to your constructor.

The ngOnInit lifecycle hook is called after the data-related properties have been checked for the first time (component inputs and outputs). See this question for a more detailed explanation.

The motivation for choosing from the ngrx repository in the constructor and dispatching from ngOnInit, as I understand it, is that the choice is part of the initialization of your component class. Since this.books$ is observable, it makes sense to initialize it in the constructor, so it is ready for use immediately after creation. Assuming that the value of bookCollection.Load() emits the value of this.books$ , you want this.books$ be observable from these books before the emitted final value.

Since you want these values ​​emitted before this.books$ , it makes sense to send the action to ngOnInit. This way you can make sure that this.books$ initialized.

This answer to a similar question may also help.

0
source share

The main reason, in my opinion, is the separation of problems. The constructor is the place where you define all the dependencies. Thus, in this case, obtaining the repository and selecting its fragment.

Submission of actions, although it is part of the logic, which can be separated from dependencies (if possible).

Think of a class with lots of dependencies and lots of action. This helps keep things separate. Everyone who reads the class can always look at the constructor to find out what dependencies are, and does not get confused with any other logic.

-one
source share

All Articles