DEV Community

Robertino
Robertino

Posted on • Originally published at auth0.com

State Management in Angular Using NGXS - Part 1

See how it’s easy to manage your #Angular application’s state using #NGXS and learn how you can use NGXS with Auth0’s SDK to handle user-related functionalities.


Intro

State management is a key component when building applications. There are various approaches by which we can manage the state in an Angular application, each with its pros and cons.

This blog post will focus on using NGXS as our state management solution. We will look at how you can use NGXS to manage your application's state by building a Recipe Admin Dashboard application. We will also learn how to secure the application using Auth0 and how it works with NGXS.

What Is NGXS

NGXS is a state management pattern and library for Angular. NGXS acts as a single source of truth for your application's state - providing simple rules for predictable state mutations.

NGXS is modeled after the CQRS pattern - a pattern implemented in state management libraries such as NgRx and Redux. NGXS combines this pattern with TypeScript's classes and decorators to create a state management library with minimal boilerplate.

How Does NGXS Work

NGXS is made up of four main components - Store, Actions, State, and Select. These components create a unidirectional circular control flow from the component to the store (via Actions) and back to the component (via Selects). The diagram below shows how the control flows in NGXS.

NGXS State Management Control Flow Diagram

Store

The Store in NGXS is a global state manager that dispatches actions to state containers and provides a way to select data slices out from the global state.

Actions

Actions express unique events that happen in our application. Actions are how the application communicates with NGXS's Store to tell it what to do.

State

States are classes that define a state container.

Select

Selects in NGXS are functions that provide the ability to slice a specific portion of the state from the global state container.

Prerequisites

Angular requires an active LTS or maintenance LTS version of Node.js. Angular applications also depend on npm packages for many features and functions. To download and install npm packages, you need an npm package manager such as npm or yarn.

This project has a server-side component that has to run in parallel when running the Frontend. Follow the instructions in the Api Express Typescript Menu repo. You can read more about setting up the server-side with Auth0 in this blog post.

This tutorial focuses on how to use Auth0 with NGXS. For more information on setting up Auth0 for Angular applications, follow the instructions on the README or refer to this blog post.

Getting Started Quickly

I created a demo application with the basic structure and components to help you implement the NGXS-related part.

Clone the demo app and check out its starter branch:

git clone -b starter git@github.com:auth0-blog/spa_angular_typescript_dashboard.git
Enter fullscreen mode Exit fullscreen mode

Once you clone the repo, make spa_angular_typescript_dashboard your current directory:

cd spa_angular_typescript_dashboard
Enter fullscreen mode Exit fullscreen mode

Install the project's dependencies:

npm i
Enter fullscreen mode Exit fullscreen mode

Run the project locally:

npm run start
Enter fullscreen mode Exit fullscreen mode

The starter project contains an admin dashboard with the ability to log in and log out using Auth0's SDK. The logged-in user can then view the dashboard and view, add, edit, and delete a menu item depending on the user's permissions.

Devtools

You can use the Redux devtools extension for Chrome or Firefox for debugging store-related operations.

To use this extension with NGXS, you'll need to add NGXS's devtools dependency to our project. You can do this using npm.

npm install @ngxs/devtools-plugin --save-dev
Enter fullscreen mode Exit fullscreen mode

Import the NgxsReduxDevtoolsPluginModule in our AppModule and configure it based on your project's requirements. For this tutorial, you'll be using their default configuration. Open app.module.ts and add the following code 👇

// src/app/app.module.ts

import { BrowserModule } from "@angular/platform-browser";
import { NgModule } from "@angular/core";
import { HttpClientModule, HTTP_INTERCEPTORS } from "@angular/common/http";
import { AuthHttpInterceptor, AuthModule } from "@auth0/auth0-angular";

// ✨ New 👇
import { NgxsReduxDevtoolsPluginModule } from "@ngxs/devtools-plugin";

import { AppRoutingModule } from "./app-routing.module";
import { AppComponent } from "./app.component";
import { NavBarModule } from "./shared";
import { environment } from "src/environments/environment";

@NgModule({
  imports: [
    BrowserModule,
    HttpClientModule,
    AuthModule.forRoot({
      ...environment.auth,
      cacheLocation: "localstorage",
      httpInterceptor: {
        allowedList: [
          `${environment.serverUrl}/api/menu/items`,
          `${environment.serverUrl}/api/menu/items/*`,
        ],
      },
    }),
    AppRoutingModule,
    NavBarModule,

    // ✨ New 👇
    environment.production ? [] : NgxsReduxDevtoolsPluginModule.forRoot(),
  ],
  declarations: [AppComponent],
  bootstrap: [AppComponent],
  providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: AuthHttpInterceptor,
      multi: true,
    },
  ],
})
export class AppModule {}
Enter fullscreen mode Exit fullscreen mode

Running the app and turning on devtools

After following the steps in this section, you should see an option to activate Redux devtools in your toolbar when you run the app. Once activated, you should see a window with an interface similar to the image below.

Redux devtools with NGXS

You can learn more about these features from their official documentation.

Install NGXS

You can use npm or yarn to install NGXS's dependencies.

Using npm

npm install @ngxs/store --save
Enter fullscreen mode Exit fullscreen mode

Using yarn

yarn add @ngxs/store
Enter fullscreen mode Exit fullscreen mode

At the time this post was written, the latest NGXS store version was 3.7.2, which will be the version we will be using throughout the tutorial.

Read more...

Discussion (0)