What is NgRx? Experiment with NgRx in Angular application – Build login function (Part 2)

Tram Ho

The previous article I went through about the main components of Ngrx and how to install it. In this article, I will guide you the Login function using ngRx.

1. Maths

We will build the login function with basic flow as follows:

  • Enter email – password to login
  • Successful login now shows success message, redirects to home page and displays username
  • Login failed shows failure message

Now let’s see with Ngrx how this problem will be solved.

2. Make it

As in the previous article I talked about the components of Ngrx. Now let’s go build it offline!

First need to create a Store folder, this Store folder will be where the Entities are stored – entities, with our problem, Entity will be the User. Each Entity will consist of 4 main components:

  • Actions
  • State
  • Reducer
  • Selector

Let’s go into each part details!

Actions (user.actions.ts)

In this file we need to define the Action

State (user.states.ts)

In this file we define the state stored in the store

Reducer (user.reducer.ts)

Here, the data will be processed before being “Pushed” into the store

Ok. Now for Reducer to work we need to “Register” Reducer with the Store

/store/index.ts

app.module.ts

At this point, we have completed two-thirds of the time. Next, we make Call Api to login.Ngrx provides a very nice package to handle this is NgxEffect (you can find out for yourself this section). Similar to the store we create folder effects

Effects

user.effects.ts

./effects/index.ts

Components

login.component.ts

login.component.html

Result

Share the news now

Source : Viblo