TL;DR
When using the selector in the component, it is recommended not to initialize them in the declaration and instead initialize them in the constructor.
export class FindBookPageComponent {
searchQuery$: Observable<string>;
books$: Observable<Book[]>;
loading$: Observable<boolean>;
error$: Observable<string>;
constructor(private store: Store<fromBooks.State>) {
this.searchQuery$ = store.pipe(
select(fromBooks.selectSearchQuery),
take(1)
);
this.books$ = store.pipe(select(fromBooks.selectSearchResults));
this.loading$ = store.pipe(select(fromBooks.selectSearchLoading));
this.error$ = store.pipe(select(fromBooks.selectSearchError));
}
search(query: string) {
this.store.dispatch(FindBookPageActions.searchBooks({ query }));
}
}
Angular Type Safety
Initializing in the constructor helps because when using the strict mode in TypeScript, the compiler will not be able to know that the selectors were initialized on ngOnInit
The strictPropertyInitialization was added by default in the --strict
mode in Angular 9.
The following checks where also added:
{
"//": "tsconfig.json",
"compilerOptions": {
"noImplicitAny": true,
"noImplicitReturns": true,
"noImplicitThis": true,
"noFallthroughCasesInSwitch": true,
"strictNullChecks": true
}
}
The strict-mode allows us to write much safe and robust application. Honestly, I think all Angular application should be written in strict-mode, but it is a little hard to understand every error messages caused by the compiler.
Top comments (2)
Instead of having one line for each declaration and another for assignment, I prefer to do all that at once. Here's how your example would look like:
Nice tip. Did you consider initializing selectors in the properties?