NgRx Course – NgRx & installation

In the previous video, we introduced state management and looked at the Redux pattern and its benefits. In this video, we’re going to see what is NgRx and we’ll start building our first Angular application with it.

According to the official documentation, NgRx is:

RxJS powered state management for Angular applications, inspired by Redux

https://github.com/ngrx/platform/tree/master/docs/store

NgRx/store follows the same principles of Redux and adds the RxJS reactive library on top of it in our Angular application.

That means that the store is the single source of truth and also that the components in our application can subscribe to changes in the state. This way the communication between components is more convenient.

Not all the state of the application should go in the Store, but all the information that needs to be shared between components should go there.

The store can be seen as a database in the front-end that we can manage with the reducers. It provides a cache so the components don’t need to connect to the server every time they’re initialized

NgRx is a collection of libraries to implement the Redux pattern in Angular applications:

  • NgRx/store – the core library
  • NgRx/effects – used to handle side effects such as communication with a back-end server
  • NgRx/router-store – to connect the angular router to NgRx store
  • NgRx/entity – used to manage record collections
  • NgRx/store-devtools – allows us to inspect and debug the application
  • NgRx/schematics – scaffolding library that provides CLI commands to generate files

We’re going to use most of these libraries throughout this course as we build our application.
Let’s see how to install NgRx in an Angular project:

Installation

First of all, make sure you have version 6 or above of npm, you can check it using the command:

$ npm -v

To install NgRx/store, we need to run the following command:

Then, to initialize the store we have to import the module in our app.module.ts file:

$ npm install @ngrx/store
import { BrowserModule } from "@angular/platform-browser";
import { NgModule } from "@angular/core";

// NgRx
import { StoreModule } from "@ngrx/store";
import { AppComponent } from "./app.component";

@NgModule({
   declarations: [AppComponent],
   imports: [
      BrowserModule,
      StoreModule.forRoot({}) // Reducer
   ],
   providers: [],
   bootstrap: [AppComponent]
})

export class AppModule {}

Once the module is imported, we have to add the declaration to the imports array, using the StoreModule.forRoot() method. Passing in the name of the reducer for the root state of the application. In this example, we don’t have a reducer yet, so we’re going to pass an empty object.

That’s all we need to install NgRx and add it to our project. In the next part of this series, we’ll look at the application we’re going to build during the rest of this course and we will start building it.