How to use ngrx/store with Ionic 4

How to use ngrx/store in Ionic 4

Using ngrx in ionic 4 is just as simple as using ngrx in angular application. Don't worry if you are not familiar with it. In this tutorial, I'll explain to you how to use ngrx in ionic 4 application.

We are going to create a very basic Todo Application to demonstrate the structure of ngrx in ionic 4 application.

At the end of this tutorial, we'll be having an ionic 4 application which is having one page called todo-list which shows the list of todos using ngrx-store.


CREATE IONIC 4 PROJECT

First of all, we need a basic ionic 4 application.

If you don't know how to create ionic 4 application, I would recommend reading my previous article: Ionic 4 For Beginners


GENERATE PAGES

We need one page to show the todo list, so we are going to create one page for it.
you can create a page in ionic by running the following command:

ionic generate page pages/todo-list

If you look into the above command, we've written pages/todo, that means we are telling ionic to generate todo-list page inside pages folder. and it generates the page with lazy loading feature.

It will create a todo-list folder in the project as follows:

ionic 4 generate page


If you'll notice the todo-list folder, it comes up with todo-list.module.ts. This is going to support lazy loading feature.

When you'll generate the page in ionic 4, all the generated page will be having its own module and its lazy-loading router configuration will be updated automatically when you'll generate the page,

so app-routing.module.ts page will be having the following line in routes array:

 { path: 'todo-list', loadChildren: './pages/todo-list/todo-list.module#TodoListPageModule' }
which tell that when /todo-list is requested then load TodoListPageModule as lazy loaded module


INSTALL NGRX

Once you have a basic setup for ionic application, then install ngrx packages.


npm install --save @ngrx/store @ngrx/effects
NOTE:  Here I am using in-memory web api, because it emulates CRUD operations over REST API
You can learn more about in memory web api here. so the following package is not compulsory to install.

npm install --save angular-in-memory-web-api

GENERATE SERVICE

The good practices to create services is inside its own module called CoreModule.
Here in CoreModule, we can create services, guards, interceptors, models and etc.

We'll create CoreModule as following structure

How to use ngrx/store in Ionic 4


You can see that I've created services folder, you can create other folder based on your need
i.e guards, interceptors etc.

Now create todo.service.ts in the app/core/services directory and copy the following code into it.


This service contains methods for getTodos (All todos), getTodo (todo By Id) and it gets data from in-memory web API because we are using in-memory web api in our example, but you can set up to get real data from live API endpoint.

In Memory DataService

we'll create inmemory dataservicce, it's not compulsory to create but since we are not using real api endpoint, we'll use it to fake the api endpoint.

Generate new file in-memory-data-service.ts and copy the following code into it.

import { Todo } from '../state/todo/todo.model';

export class InMemoryDataService {
    createDb() {
        const todos: Array = [
            { id: 1, name: "Shopping" },
            { id: 2, name: "Meeting" }
        ];

        return { todos };
    }
}

Core Module

Now create a new file called core.module.ts. Here we'll import InMemoryWebApiModule and will define all services created in this module, In our case, we have created on one service called todo.service.ts
Copy the following code into core.module.ts



SETUP NGRX 

First, create a new folder called state in app folderthis folder is responsible for containing the state for all modules that the app contains.

To easily distinguish the state of all modules, we'll create a separate folder for each module inside state folder.

In our case, we'll create todo folder inside state folder so it will look like the following structure.

How to use ngrx/store in Ionic 4


Now we'll create few files of ngrx setup in todo folder, so at the end, the folder will look like the following:
Getting Started NgRx with Ionic 4
Add caption

Ngrx Actions

At first, we are creating the string const variables as following:

export const GET_ALL_TODOS = '[TODO] Get All Todos';

We are exporting this const, because we will need these in the reducer and effects later.

We will use this const string to define the type of the actions.

Create todo.actions.ts file in app/state/todo directory, this file is responsible for creating actions which are related to todo module.

Here we've created few actions to get todo list from API. and there is a success and fail action which will be called from effects based on the response of API.

Now copy the following code in your todo.action.ts


Ngrx Reducers

Now copy the following code in your todo.reducer.ts


Ngrx Effects

Effect will communicate with service. It will call service and based on the response it will dispatch the success or fail action.

If you'll look into getAllTodos$ effect, you can see that it is calling todoservice method getTodos
and based on its response it will dispatch either GetAllTodoSuccess or GetAllTodosFail.

Copy following code in your todo.effects.ts



Ngrx Selector

The task of a selector is to select the property from the ngrx state, and we can call this selector from our component to fetch the data of ngrx state.

For example:


export const getAllTodos = createSelector(
    getTodosState,
    fromTodos.getAllTodos
  );

Here you can see that we are telling ngrx that select getAllTodos from getTodoState.

So It will call getAllTodos
selector which is defined in reducer.

Now copy the following code in your index.ts




Todo Model

Generate todo model as following in your todo.model.ts



Root State

Generate AppState interface to represent the entire state of the application. You can add other modules same as todo module.

Copy the following code in app.reducer.ts in app/state directory.



State Module

Now we'll create the module for the ngrx state called StateModule, where we'll define our reducers and effects.

Create a new file called state.module.ts in app/state directory and copy the following code into it.


App Module

As of now, we've created StateModule and CoreModule, we need to import it in the main module called AppModule

Now update your AppModule as following:



TODO LIST PAGE

Now, ngrx setup is completed and it's time to update our ionic page to fetch a list of todos using ngrx.

Update todo-list.page.ts as following:



In the above code you can see that we are fetching data from selectors:

this.todos$ = this.store.select(getAllTodos);


and update todo-list.page.html as following:



Our todo app is ready now
.
Run the application using ionic serve. It will run the ionic app and open /todo-list url and it will display the following result.
ngrx/store in ionic 4


Here you can see that it has displayed two results Shopping and Meeting from in-memory-web-service.

Download full tutorial of todo app from github

Thanks for reading the article.


Also, read my other articles:




How to use ngrx/store with Ionic 4 How to use ngrx/store with Ionic 4 Reviewed by Borad Akash on July 30, 2018 Rating: 5

No comments:

Powered by Blogger.