Last active
December 28, 2019 17:03
-
-
Save ThomasBurleson/d245aba022646bc28223fbb46cdd5e76 to your computer and use it in GitHub Desktop.
Compressing View Logic with Facades
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* | |
* Snippet from blog article: https://auth0.com/blog/ngrx-facades-pros-and-cons/ | |
* | |
*/ | |
@Component({ | |
selector: 'abl-books-page', | |
changeDetection: ChangeDetectionStrategy.OnPush, | |
template: ` | |
<mat-card> | |
<mat-card-title>My Collection</mat-card-title> | |
<mat-card-actions> | |
<button mat-button raised color="accent" (click)="logout()">Logout</button> | |
</mat-card-actions> | |
</mat-card> | |
<abl-book-preview-list [books]="books$ | async"></abl-book-preview-list> | |
}) | |
export class BooksPageComponent implements OnInit { | |
books$: Observable<Book[]>; | |
constructor(private booksFacade: BooksFacadeService) { | |
this.books$ = booksFacade.allBooks$; | |
} | |
ngOnInit() { | |
this.booksFacade.dispatch(new BooksPageActions.Load()); | |
} | |
} | |
export class BooksPageComponent implements OnInit {
books$: Observable<Book[]> = this.facade.allBooks$;
constructor(private facade: BooksFacadeService) { }
}
vs
export class BooksPageComponent implements OnInit {
books$: Observable<Book[]> = this.store.select(getAllBooks);
constructor(private store: Store<{}>) { }
}
How is it any different other than another layer of BooksFacadeService
which literally does the same thing.
View components never know about this complexity.
View components never know about the complexity behind selectors as well - they just consume them. Selectors
are already the abstraction and encapsulation layer.
I would've done
export class BooksPageComponent {
constructor(public facade: BooksFacadeService) { }
}
and
<abl-book-preview-list [books]="facade.allBooks$ | async"></abl-book-preview-list>
Even simpler! Thanks for bringing us this awesome pattern, Thomas!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Facades have super powers regarding how they encapsulate and use/combine NgRx selectors (aka queries). View components never know about this complexity.
Facades also provide another very important feature: Facades enable view-layer code compression for a super clean, maintainable component implementations.
To code-compress the above example, let's use:
books$
loadBooksPage()
books-page.component.ts
Even better, developers should use
ngrx/router
and Effects to auto-load BooksPage data whenthe BooksPageComponent activates. This would free the view component from load logic also.
Nx DataPersistence makes this super easy. Or just use
ROUTER_NAVIGATION
:books.effects.ts