Software systems to innovate and grow

Authentication in Angular with NgRx Part 1

By Engineering Team September 19, 2018 10 mins read

In this article I am going to walk you through what the NgRx library is, as well as share common use case scenarios for each application. The scope of the example project will cover the login of the application using token based authentication. When the user logs in, the token will be stored in local storage. When he or she logs out, the token will be removed.

For this tutorial we will use:

  • Angular 6
  • Angular CLI (for the project creation)
  • NPM (to install dependencies)
  • NgRx
  • Bootstrap (only for some predefined styles)

First I’ll walk you through an introduction of some basic concepts related to functional programming and state management that are the core of the Redux based library NgRx.

Functional Programming and State Management

The functional programming paradigm considers computation as the evaluation of mathematical functions. It prevents state changing and the use of mutable data.
In other words, by using a functional programming style,  you get more control and reliability of the app state. It’s based on the idea of pure functions , meaning functions with the same output for the same arguments. The return value of pure functions depends only on the arguments passed to that function. Debugging the application becomes more user friendly because you’ll have improved your control over the changes. The chances of generating unexpected behaviours and bugs are reduced because of this control and restriction of ways the application state can be changed. As a result, your application gets larger and more complex , making the state management a bit harder. This is where libraries come in to help tackle this issue.

NgRx- The Reactive and Highly Performant Redux State Management for Angular Apps

NgRx – is a state management library for Angular, inspired by Redux. It uses the reactive programming library RxJs to achieve highly performant applications and provide a more robust development experience.

It’s based on three principles:

  1. The state of the application is immutable.
  2. The only way of achieving state mutation is by dispatching actions.
  3. The Reducer functions are the only ones that have the ability to change an application state.

Add it to your project:

NgRx Store

NGRX Store makes state management easier and more predictable by handling state in a single, immutable data store.

It is composed of the following elements:

  • Store: a single immutable data structure that contains the app state.
  • Action: an object that describes changes to the state.
  • Reducer: a pure function that creates a new state. Takes form as arguments of the previous state and uses the next action to return to the new state. The state is accessed with the Store, an observable of state and an observer of actions.

Adding it to your project:

Authentication in Angular with NRGX Part 1

Login Project Creation

Below are descriptions of each file added to the project, with the code needed to achieve the authentication example:

Defining the User Model

The file is added inside a models folder in the app folder.

  • app/
    • app.module.ts
    • app.component.ts
    • models/
      • user.ts

A user will enter an email, a password and web token.

Adding Service to Handle the Authentication

You’ll need a way to communicate with the server to create the login. A Http Post request would be a way to communicate with an api, but since we don’t have a server to simplify the process, an observable is defined in the login method. This works in an asynchronous way, returning an Observable the same way the Http.post() does. The example compares the user email and password from the login form with a testUser, declared here. If the email and password are the same it will return the email and token. If no errors appear it will return with the real response of a login endpoint.

Add the file inside a new services folder inside the app folder.

  • app/
    • app.module.ts
    • app.component.ts
    • services/
    • authentication.services.ts

Defining the Building Blocks of NgRx

You’ll need to create a store folder to contain all the files related to the actions, the reducer, the application state and the effects.

The project directory should look like this:

  • app/
    • app.module.ts
    • app.component.ts
    • store/
      • actions/
      • effects/
      • reducers/

Defining the Actions

Actions describe changes to the state, and each one has a payload.
Since this example only covers the login and logout of an application, you will need to add four actions to the actions file.
LOGIN, LOGIN_SUCCESS, LOGIN_FAILURE and LOGOUT.
Export each one of the actions as a class.

Add the file inside the actions folder.

  • app/
    • store/
      • actions/
        • authentication.actions.ts

Defining the Reducer

Now it’s time to define the reducer function— it’s the only one that has the ability to change its application state. It takes the already defined actions and depending on each action, returns to a new state. Here we define an initial state to be used as the first state of the application. Its loaded from local storage since the token and user are maintained there. If the user reloads the application home page while being logged in, the application will recognize his current session. This adds the file inside the reducers folder.

  • app/
    • store/
      • actions/
      •      authentication.actions.ts
      • reducers/
      •      authentication.reducer.ts

Defining the Application State

Let’s define the top level state interface. This is a map of keys to the inner state types defined in the reducer.

The file is added inside the store folder at the same level of the other NgRx folders needed.

  • app/
    • store/
      • actions/
      •      authentication.actions.ts
      • effects/
      • reducers/
      •      authentication.reducer.ts
      • app.state.ts

    Conclusion

    In this article you have been introduced to NgRx, the state management library for Angular inspired by Redux and how it can be used to deal with an app authentication scenario. You now have defined the model, and the application state using NgRx Store to manage the state. Each one of these blocks plays an important role in how to manage the app state mutation. Together with functional programming and NgRx you have the capacity to monitor and track the user interactions while understanding the reasoning behind changing the state while dispatching an action. This way, you’ll have much more control over the application state. Don’t miss part two of this article to learn about the creation of the remaining components while the authentication project is completed.