Sign Up
Hero

NgRx Facades: Pros and Cons

Learn about the facade pattern, why you may or may not want to use one with NgRx, and how to create a facade.

You may have heard recently about a topic whizzing around the Angular community: facades in NgRx. I thought it’d be a great idea to write an article to talk through this issue. Let’s learn what facades are, the arguments for and against them, and how to implement one. (You can find the sample code in this repository.)

What are facades?

I took this picture of the facade of Buckingham Palace when I was in London this November. Even though I know by looking at it that it’s Buckingham Palace, I have no idea what’s inside — and those guards are there to make sure I don’t find out.

In code, the term “facade” refers to the facade pattern, which is a structural design pattern from the famous book Design Patterns (usually called the “Gang of Four” in reference to the authors). Just like the front of a building hides what’s inside to passersby, a facade in code hides the complexity of underlying services by only exposing certain methods. You’ll often hear this hiding of complexity referred to as “adding a layer of abstraction.” An abstraction is a simpler and more general model of something that only provides what its consumer needs to know.

The facade pattern, and abstraction in general, is similar to the relationship between you and your car. You only need to know that when you turn the key and press the gas pedal, your car moves forward. You don’t need to care about the underlying mechanics of the engine or the science of combustion in order to go to the grocery store.

Here's how the facade pattern can be represened in a diagram:

Source

You can see here how the clients don't know anything about the other services. They simply call doSomething() and the facade handles working with the services behind the scenes.

Facades in NgRx

Recently, there has been a lot of discussion about whether or not to use a facade with NgRx to hide away bits like the store, actions, and selectors. This was sparked by an article by Thomas Burleson called NgRx + Facades: Better State Management. A facade is basically just an Angular service that handles any interaction with the store. When a component needs to dispatch an action or get the result of a selector, it would instead call the appropriate methods on the facade service.

This diagram illustrates the relationship between the component, the facade, and the rest of NgRx:

Let’s take a look at an example to understand this better. Here’s the BooksPageComponent from the sample code for my NgRx Authentication Tutorial (I’ve hidden the code inside of the Component decorator to make it easier to read):

// src/app/books/components/books-page.component.ts
import { ChangeDetectionStrategy, Component, OnInit } from '@angular/core';
import { select, Store } from '@ngrx/store';
import { Observable } from 'rxjs';

import * as BooksPageActions from '../actions/books-page.actions';
import { Book } from '../models/book';
import * as fromBooks from '../reducers';
import { Logout } from '@app/auth/actions/auth.actions';

@Component({
 /* ...hidden for readability */
})
export class BooksPageComponent implements OnInit {
  books$: Observable<Book[]>;

  constructor(private store: Store<fromBooks.State>) {
    this.books$ = store.pipe(select(fromBooks.getAllBooks));
  }

  ngOnInit() {
    this.store.dispatch(new BooksPageActions.Load());
  }

  logout() {
    this.store.dispatch(new Logout());
  }
}

This component imports the store, some actions, and some reducers. It dispatches the Load action during ngOnInit and uses a selector for the books in the constructor. It also dispatches an action when the user logs out.

If we were instead using a facade in the component, the class would look something like this (I’ll leave out the imports and decorator for the sake of brevity):

// src/app/books/components/books-page.component.ts
// above remains the same except for the imports
export class BooksPageComponent implements OnInit {
  books$: Observable<Book[]>;

  constructor(private booksFacade: BooksFacade) {
    this.books$ = this.booksFacade.allBooks$;
  }

  ngOnInit() {
    this.booksFacade.loadBooks();
  }

  logout() {
    this.booksFacade.logout();
  }
}

We’ve replaced the selector with an observable on the booksFacade service. We’ve also replaced both action dispatches with calls to methods on the booksFacade service.

The facade would look like this (again leaving out the imports for the sake of brevity):

// imports above
@Injectable()
export class BooksFacade {
  allBooks$: Observable<Book[]>;

  constructor(private store: Store<fromBooks.State>) {
    this.allBooks$ = store.pipe(select(fromBooks.getAllBooks));
  }

  getBooks() {
    this.store.dispatch(new BooksPageActions.Load());
  }

  logout() {
    this.store.dispatch(new Logout());
  }
}

Looking at the component code in isolation, you’d have no idea that this Angular application is using NgRx for state management. So, is that a good thing or a bad thing? Let’s talk about some pros and cons to this approach.

The Case for Facades

Let’s first consider some pros of the facade pattern for NgRx.

Pro #1: Facades provide a better developer experience.

One of the biggest arguments for using the facade pattern is its boost to developer experience. NgRx often gets flack for requiring a lot of repetitive code for setup and for the difficulty of maintaining and scaling a lot of moving parts. Every feature requires changes to state, the store, actions, reducers, selectors, and effects. By adding a layer of abstraction through the facade, we decrease the need to directly interact with these pieces. For example, a new developer writing a new feature listing books could just inject the BooksFacade and call loadBooks() without needing to worry about learning the intricacies of the store.

Pro #2: The facade pattern is easier to scale than plain NgRx.

The second argument for the facade pattern is how easy it is to scale. Let’s say, for example, we needed to develop seven new features for a large application. Several of those features would probably overlap in some of the ways they affect the state of the application, as well as in the data they consumed. We could cut out a lot of repetitive work by using facades:

  • First, we'd determine the smallest number of state changes we need to make based on unique use cases.
  • Next, we'd add them to the right places in the application-wide NgRx setup files (like changes to the application state or reducers).
  • Finally, we'd appropriate methods and selectors to our facade.

The seven new features could then be added quickly while letting the facade worry about the underlying NgRx pieces.

"Using facades in NgRx can increase dev productivity and make apps easier to scale."

Tweet This

The Case Against Facades

This reduced friction in development and scaling really sound great, but is everything a bed of roses? Let’s take a look at the other side of the argument.

Con #1: Facades break the indirection of NgRx.

The first time I saw facades used with NgRx, I had an immediate response of, “Wait, we just spent all this time setting up NgRx actions, reducers, and effects, but now we’re hiding all of that away with a service?” It turns out that gut feeling I had is one of the main arguments against using facades.

While NgRx does get criticized for having a lot of moving parts, each of those parts has been designed to perform a specific function and communicate with other parts in a specific way. At its core, NgRx is like a messaging system. When a user clicks a “Load Books” button, the component sends a message (an action) that says, “Hey, load some books!” The effect hears this message, fetches the data from the server, and sends another message as action: “Books are loaded!” The reducer hears this message and updates the state of the application to “Books loaded.”

We call this indirection. Indirection is when part of your application is responsible for something, and the other pieces simply communicate with it through messaging. Neither the reducer nor the effects know about the button that was pressed. Likewise, the reducer doesn’t know anything about where the data came from or the address of the API endpoint.

When you use facades in NgRx, you circumvent this design (at least in practice). The facade now knows about dispatching actions and accessing selectors. At the same time, the developer working on the application no longer knows anything about this indirection. There’s simply now a new service to call.

Con #2: Facades can lead to reusing actions.

With NgRx’s indirection circumvented and hidden away from developers, it becomes very tempting to reuse actions. This is the second major disadvantage to the facade pattern.

Let’s say we’re working on our books application. We’ve got two places where a user can add a new book: 1) the list of books and 2) a book’s detail page. It would be tempting to add a method to our facade called addBook() and use it to dispatch the same action in both of these instances (something like [Books] Add Book).

However, that would be an example of poor action hygiene. When we come back to this code in a year or two because of a bug that’s cropped up, we won’t know when we’re debugging where [Books] Add Book came from. Instead, we’d be better off following Mike Ryan’s advice in his ng-conf 2018 talk Good Action Hygiene. It’s better to use actions to capture events, not commands. In our example, our booksReducer could simply have an additional case:

function booksReducer(state, action){
  switch (action.type) {
    case '[Books List] Add Book':
    case '[Book Detail] Add Book':
      return [...state, action.book];
    default:
      return state;
  }
}

When writing actions, we always want to focus on clarity over brevity. Good actions are actions you can read after a year and tell where they are being dispatched.

When it comes to the facade pattern, we can mitigate this problem by creating a dispatch method in our facade instead of abstracting away actions. In our example above, instead of having a generic addBook() method, we’d call facadeService.dispatch(new AddBookFromList()) or facadeService.dispatch(new AddBookFromDetail()). We lose a little bit of abstraction by doing this, but it will save us headaches in the future by following best practices for action creation.

So, which is it?

Facades can greatly speed up development time in large NgRx apps, which keeps developers happy and makes scaling up a lot easier. On the other hand, the added layer of abstraction can defeat the purpose of NgRx’s indirection, causing confusion and poor action hygiene. So, which wins out?

All developers at some point in their career will learn that increased abstraction always comes at a price. Abstraction trades transparency for convenience. This may turn up in difficulty debugging or difficulty maintaining, but it will come up at some point. It’s always up to you and your team to determine whether that trade-off is worth it and how to deal with any downsides. Some folks in the Angular community argue that the benefits of the facade pattern outweigh the cost of increased abstraction, and some argue they don’t.

I believe the facade pattern certainly has a place in NgRx development, but I’d offer two caveats. If you’re going to use facades with NgRx:

  1. Make sure your developers understand the NgRx pattern, how its indirection works, and why you’re using a facade, and
  2. Promote good action hygiene by using a dispatch method in your facade service instead of abstracting actions.

By teaching your teammates the NgRx pattern while also using a facade, you’ll save yourself some headaches when things start to break. By using a dispatch method in your facade, you’ll mitigate the tendency to reuse actions at the expense of keeping your code readable and easy to debug.

"Even though using facades in NgRx can be really helpful, it's important to keep good action hygiene in mind and not reuse actions."

Tweet This

Implementing a Facade

Now that we know why we may or may not want to use a facade with NgRx, let’s create one. We’re going to add a facade to a simple books application and use the facade to simplify the component that lists the book collection. We’ll also use good action hygiene by using the dispatch pattern described above.

Set Up the Application

To get started, we'll need to be sure Node and npm are installed. We’ll also need the Angular CLI:

npm install -g @angular/cli

The code for this tutorial is at the Auth0 Blog repository. Here are the commands we’ll need:

git clone https://github.com/auth0-blog/ngrx-facades.git
cd ngrx-facades
npm install
git checkout 8e24360

Test the Application

We should now be able to run ng serve, navigate to http://localhost:4200, and click “See my book collection.”

Add the Facade Service

Since a facade is just a service, we can generate our initial code with the Angular CLI:

ng generate service /books/services/books-facade --spec=false

We’ll now have a services folder inside of our books folder with a file called books-facade.service.ts. Opening it, we’ll see the following:

// src/app/books/services/books-facade.service.ts
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class BooksFacadeService {

  constructor() { }
}

Note: You’re welcome to drop Service from the class name. Some people also remove service from the file name and move this file somewhere more related to state to prevent confusion with HTTP services. I’m leaving those details up to you and sticking with some simple defaults.

Let’s think about what we initially want our new facade to do for us. We’re going to use it in the BooksPageComponent we discussed above. Let’s remind ourselves what that component class looks like:

// src/app/books/components/books-page.component.ts
// Omitting Component decorator and imports for brevity.
export class BooksPageComponent implements OnInit {
  books$: Observable<Book[]>;

  constructor(private store: Store<fromBooks.State>) {
    this.books$ = store.pipe(select(fromBooks.getAllBooks));
  }

  ngOnInit() {
    this.store.dispatch(new BooksPageActions.Load());
  }
}

Our component does the following:

  • Calls a selector for the books
  • Dispatches a Load action from the store during the ngOnInit lifecycle hook.

Let’s implement replacements for these in our facade. We’ll be able to simply copy over quite a bit of this code with a few modifications.

We know that we need to inject the Store in the constructor, which will take the State exported from src/app/books/reducers/books.ts just as it is in the BooksPageComponent. We also know we’ll need a dispatch method that takes an Action (which we’ll need to import). Let’s update our facade accordingly by importing what we need and adding those things:

// src/app/books/services/books-facade.service.ts
import { Injectable } from '@angular/core';
import { Store, Action } from '@ngrx/store';

import * as fromBooks from '../reducers';

@Injectable({
  providedIn: 'root'
})
export class BooksFacadeService {

  constructor(private store: Store<fromBooks.State>) { }

  dispatch(action: Action) {
    this.store.dispatch(action);
  }
}

Notice that we’re using the same imports and the same injection of the store as in the component.

Finally, let’s initialize a new observable for the books and use a selector in the constructor. We’ll basically copy over what we’ve got in the component right now, but let’s change the name of the observable to allBooks$ just to be clear. We’ll also need to import Observable from rxjs, add select to our imports from ngrx/store, and import the Book model. The finished code will look like this:

// src/app/books/services/books-facade.service.ts
import { Injectable } from '@angular/core';
import { Store, Action, select } from '@ngrx/store';
import { Observable } from 'rxjs';

import * as fromBooks from '../reducers';
import { Book } from '../models/book';

@Injectable({
  providedIn: 'root'
})
export class BooksFacadeService {
  allBooks$: Observable<Book[]>;

  constructor(private store: Store<fromBooks.State>) {
    this.allBooks$ = store.pipe(select(fromBooks.getAllBooks));
  }

  dispatch(action: Action) {
    this.store.dispatch(action);
  }
}

Our facade is done! Now let’s update our books page component.

Update the Books Page

The first thing we’ll do to update the BooksPageComponent is replace the injection of the store with the BooksFacadeService:

// src/app/books/components/books-page.component.ts
// no changes to above imports
import { BooksFacadeService } from '../services/books-facade.service';

@Component({
// hidden, no changes
})
export class BooksPageComponent implements OnInit {
  books$: Observable<Book[]>;

  constructor(private booksFacade: BooksFacadeService) {
     this.books$ = store.pipe(select(fromBooks.getAllBooks));
  }

  ngOnInit() {
    this.store.dispatch(new BooksPageActions.Load());
  }
}

Of course, we’ll now see red squiggles in our editor underneath the references to the store. We can fix those by replacing the selector with booksFacade.allBooks$ and the other reference to store inside of ngOnInit with the booksFacade. The rest will remain unchanged. Cleaning up the imports, the finished code will look like this (again, omitting the decorator since there are no changes):

import { ChangeDetectionStrategy, Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';

import * as BooksPageActions from '../actions/books-page.actions';
import { Book } from '../models/book';
import { BooksFacadeService } from '../services/books-facade.service';

@Component({
  // hidden, no changes
})
export class BooksPageComponent implements OnInit {
  books$: Observable<Book[]>;

  constructor(private booksFacade: BooksFacadeService) {
    this.books$ = booksFacade.allBooks$;
  }

  ngOnInit() {
    this.booksFacade.dispatch(new BooksPageActions.Load());
  }
}

And that’s it! We’re no longer using the store in this component. We should still be able to run ng serve and look at the book list. To double-check that the facade is working, we can set a breakpoint on the dispatch method in the service. It should trigger when the books load.

Because this is such a simple example, we didn’t get a ton of benefit to using the facade here. However, it’s easy to imagine how much of a lifesaver this would be if this component was using five selectors at a time and there were seven other components doing the same! You now know everything you need to scale this example up. Try adding more selectors or actions to the application!

Remember, you can access the finished sample code here.

Conclusion

The facade pattern can be extremely helpful when trying to build large Angular applications that use NgRx for state management. At the same time, it’s good to be aware of the pitfalls when using this approach. Increased abstraction can cause increased opacity if you’re not careful and can also lead to some bad habits when it comes to creating and using actions. You can avoid those pitfalls by keeping your team well-versed in the NgRx pattern, teaching new developers the reasons for using facades, and by using a dispatch method in your facade instead of abstracting actions. Good luck and happy coding!

Aside: Authenticate an Angular App with Auth0

By integrating Auth0 in your Angular application, you will be able to manage user identities, including password resets, creating, provisioning, blocking, and deleting users. It requires just a few steps.

Set up an Auth0 application

First, sign up for a free account here. Then, set up an Auth0 application with the following steps:

  1. Go to your Applications section of the Auth0 Dashboard and click the "Create Application" button.
  2. Name your new app and select "Single Page Web Applications" as the application type.
  3. In the Settings for your new Auth0 app, add http://localhost:4200 to the Allowed Callback URLs, Allowed Web Origins, and Allowed Logout URLs. Click the "Save Changes" button.
  4. If you'd like, you can set up some social connections. You can then enable them for your app in the Application options under the Connections tab. The example shown in the screenshot above uses username/password database, Facebook, Google, and Twitter.

Note: Set up your own social keys and do not leave social connections set to use Auth0 dev keys, or you will encounter issues with token renewal.

Add dependencies and configure

In the root folder of your Angular project, install the auth0-spa-js library by typing the following command in a terminal window:

npm install @auth0/auth0-spa-js

Then, edit the environment.ts file in the src/environments folder and add the CLIENT_DOMAIN and CLIENT_ID keys as follows:

// src/environments/environment.ts

export const environment = {
  production: false,
  auth: {
    CLIENT_DOMAIN: 'YOUR_DOMAIN',
    CLIENT_ID: 'YOUR_CLIENT_ID',
  },
};

export const config = {};

Replace the YOUR_DOMAIN and YOUR_CLIENT_ID placeholders with the actual values for the domain and client id you found in your Auth0 Dashboard.

Add the authentication service

Authentication logic in your Angular application is handled with an AuthService authentication service. So, use Angular CLI to generate this new service by running the following command:

ng generate service auth

Now, open the src/app/auth.service.ts file and replace its content with the following:

//src/app/auth.service.ts

import { Injectable } from '@angular/core';
import createAuth0Client from '@auth0/auth0-spa-js';
import Auth0Client from '@auth0/auth0-spa-js/dist/typings/Auth0Client';
import {
  from,
  of,
  Observable,
  BehaviorSubject,
  combineLatest,
  throwError,
} from 'rxjs';
import { tap, catchError, concatMap, shareReplay } from 'rxjs/operators';
import { Router } from '@angular/router';
import { environment } from './../environments/environment';

@Injectable({
  providedIn: 'root',
})
export class AuthService {
  // Create an observable of Auth0 instance of client
  auth0Client$ = (from(
    createAuth0Client({
      domain: environment.auth.CLIENT_DOMAIN,
      client_id: environment.auth.CLIENT_ID,
      redirect_uri: `${window.location.origin}`,
    }),
  ) as Observable<Auth0Client>).pipe(
    shareReplay(1), // Every subscription receives the same shared value
    catchError((err) => throwError(err)),
  );
  // Define observables for SDK methods that return promises by default
  // For each Auth0 SDK method, first ensure the client instance is ready
  // concatMap: Using the client instance, call SDK method; SDK returns a promise
  // from: Convert that resulting promise into an observable
  isAuthenticated$ = this.auth0Client$.pipe(
    concatMap((client: Auth0Client) => from(client.isAuthenticated())),
    tap((res) => (this.loggedIn = res)),
  );
  handleRedirectCallback$ = this.auth0Client$.pipe(
    concatMap((client: Auth0Client) => from(client.handleRedirectCallback())),
  );
  // Create subject and public observable of user profile data
  private userProfileSubject$ = new BehaviorSubject<any>(null);
  userProfile$ = this.userProfileSubject$.asObservable();
  // Create a local property for login status
  loggedIn: boolean = null;

  constructor(private router: Router) {
    // On initial load, check authentication state with authorization server
    // Set up local auth streams if user is already authenticated
    this.localAuthSetup();
    // Handle redirect from Auth0 login
    this.handleAuthCallback();
  }

  // When calling, options can be passed if desired
  // https://auth0.github.io/auth0-spa-js/classes/auth0client.html#getuser
  getUser$(options?): Observable<any> {
    return this.auth0Client$.pipe(
      concatMap((client: Auth0Client) => from(client.getUser(options))),
      tap((user) => this.userProfileSubject$.next(user)),
    );
  }

  private localAuthSetup() {
    // This should only be called on app initialization
    // Set up local authentication streams
    const checkAuth$ = this.isAuthenticated$.pipe(
      concatMap((loggedIn: boolean) => {
        if (loggedIn) {
          // If authenticated, get user and set in app
          // NOTE: you could pass options here if needed
          return this.getUser$();
        }
        // If not authenticated, return stream that emits 'false'
        return of(loggedIn);
      }),
    );
    checkAuth$.subscribe();
  }

  login(redirectPath: string = '/') {
    // A desired redirect path can be passed to login method
    // (e.g., from a route guard)
    // Ensure Auth0 client instance exists
    this.auth0Client$.subscribe((client: Auth0Client) => {
      // Call method to log in
      client.loginWithRedirect({
        redirect_uri: `${window.location.origin}`,
        appState: { target: redirectPath },
      });
    });
  }

  private handleAuthCallback() {
    // Call when app reloads after user logs in with Auth0
    const params = window.location.search;
    if (params.includes('code=') && params.includes('state=')) {
      let targetRoute: string; // Path to redirect to after login processed
      const authComplete$ = this.handleRedirectCallback$.pipe(
        // Have client, now call method to handle auth callback redirect
        tap((cbRes) => {
          // Get and set target redirect route from callback results
          targetRoute =
            cbRes.appState && cbRes.appState.target
              ? cbRes.appState.target
              : '/';
        }),
        concatMap(() => {
          // Redirect callback complete; get user and login status
          return combineLatest([this.getUser$(), this.isAuthenticated$]);
        }),
      );
      // Subscribe to authentication completion observable
      // Response will be an array of user and login status
      authComplete$.subscribe(([user, loggedIn]) => {
        // Redirect to target route after callback processing
        this.router.navigate([targetRoute]);
      });
    }
  }

  logout() {
    // Ensure Auth0 client instance exists
    this.auth0Client$.subscribe((client: Auth0Client) => {
      // Call method to log out
      client.logout({
        client_id: environment.auth.CLIENT_ID,
        returnTo: `${window.location.origin}`,
      });
    });
  }
}

This service provides the properties and methods necessary to manage authentication across your Angular application.

Add the login and logout buttons

To add a new component that allows you to authenticate with Auth0, run the following command in a terminal window:

ng generate component login-button

Open the src/app/login-button/login-button.component.ts file and replace its content with the following:

//src/app/login-button/login-button.component.ts

import { Component, OnInit } from '@angular/core';
import { AuthService } from '../auth.service';

@Component({
  selector: 'app-login-button',
  templateUrl: './login-button.component.html',
  styleUrls: ['./login-button.component.css'],
})
export class LoginButtonComponent implements OnInit {
  constructor(public auth: AuthService) {}

  ngOnInit() {}
}

Next, define the component's UI by replacing the content of the src/app/login-button/login-button.component.html with the following markup:

<!-- src/app/login-button/login-button.component.html -->
<div>
  <button (click)="auth.login()" *ngIf="!auth.loggedIn">Log In</button>
  <button (click)="auth.logout()" *ngIf="auth.loggedIn">Log Out</button>
</div>

Finally, put the <app-login-button></app-login-button> tag within the src/app/app.component.html file, wherever you want the component to appear.

Your Angular application is ready to authenticate with Auth0!

Check out the Angular Quickstart to learn more about integrating Auth0 with Angular applications.