This article assumes the readers’ knowledge of Angular and NgRx.
NgRx Facade Pattern
The Facade pattern (in NgRx) is a well-known pattern that was popularized from this blog post by Thomas Burleson.
Essentially, instead of having our Components to interact with the NgRx Store via Actions
and Selectors
, we would abstract these interactions via a Service
called the Facade.
The following code snippet is a Component interacting with the NgRx Store directly.
@Component({
/* hidden for readability */
})
export class BooksPageComponent {
readonly books$ = this.store.select(booksSelector);
constructor(private store: Store) {}
addBook(book: Book) {
this.store.dispatch(BooksPage.addBook(book));
}
deleteBook(id: string) {
this.store.dispatch(BooksPage.deleteBook(id));
}
updateBook(book: Book) {
this.store.dispatch(BooksPage.updateBook(book));
}
}
With a Facade, we will end up with the following
@Injectable({ providedIn: "root" })
export class BooksFacade {
readonly books$ = this.store.select(booksSelector);
constructor(private store: Store) {}
addBook(book: Book) {
this.store.dispatch(addBook(book));
}
deleteBook(id: string) {
this.store.dispatch(deleteBook(id));
}
updateBook(book: Book) {
this.store.dispatch(updateBook(book));
}
}
Then our Component uses the Facade
@Component({
/*...*/
})
export class BooksPageComponent {
readonly books$ = this.booksFacade.books$;
constructor(private booksFacade: BooksFacade) {}
addBook(book: Book) {
this.booksFacade.addBook(book);
}
deleteBook(id: string) {
this.booksFacade.deleteBook(id);
}
updateBook(book: Book) {
this.booksFacade.updateBook(book);
}
}