How to setup NgXs library inside the angular app (Learn It in 22 Steps)

How to setup NgXs library inside the angular app (Learn It in 22 Steps)

This project describes how to set up the NgXs library inside the angular project. Please follow the below steps.

Step 0. Before starting the setup, I want to tell you something, we can call the API directly from the angular app and display it inside the component directly.

But here, is why we are using either NgRx or NgXs library inside the angular.

  • We are using NgRx or NgXs for storing the data inside the state object as the concept of the source of truth principle.
  • If we are storing the data inside the state, we can be able to access it from any component.
  • Inside NgRx/NgXs we are calling the API to get the data and store it in the state. But here one advantage is there i.e., if the API response is matched with the existing data the store won’t update the state.

Compared to NgRx, NgXs have less setup and less code in that way, we can learn it easily

Before that you don’t know about Redux or NgRx please read my NgRx Setup article.

Here, I’m telling you about NgXs and which is a typescript-based syntax, The NgXs contain mainly two files

  • Actions- Actions are in the sense of calling the actions like run, catch, and drop.
  • States- States are used to create a state object and to update the state by using Action listeners. Also, we can create a selector to get the updated data from the state. (So here there is no concept of reducer and effects)

Step 1: Create an angular project by using the below command.

ng new angular-ngxs-simple-example

Step 2. After successful creation of the angular app, change the file directory to project-name. “cd angular-ngxs-simple-example”

Open project in vs code using “code .” in terminal or open within “vs code”. Then run the project using “ng serve” in the terminal (To avoid errors always do “npm install” before “ng serve”). Open the project in chrome using [***localhost:4200***](http://localhost:4200/)

Step 3. Open “app.component.html” in vs code and remove the content which is created by “Angular CLI” while creating the app.

Step 4. For adding “NgXs library”, Please install all the below libraries.

npm install @ngxs/store --save   
npm install @ngxs/logger-plugin --save-dev   
npm install @ngxs/devtools-plugin --save-dev

Step 5. After that add bootstrap by using the below command.

npm install bootstrap@4.3.1

Step 6. Open the angular.json file and add the bootstrap.min.css path inside the styles array of the angular.json file.

Step 7. After all the above steps are done, please do “npm install” and “ng serve” and check if any error is occurring or not. If no error, please ignore this step completely.

Step 8. Open app.module.ts and update the imports array in the following way.

The above screenshot states that import the NgXs module and also update the imports array.

Step 9. Create a store folder under the app folder and also create actions, and states folder under the store folder. Parallelly create the pokeman.action.ts and pokeman.states.ts under their respective folders in the following way.

Step 10. Create a service file to call the API and store the data inside the store. To get the data from API am using the Pokeman API as the backend.

  • Create a service file under the app/store/apis folder by using the below command.
ng generate service pokeman
  • After that open app.module.ts, Import HttpClientModule and add inside the imports array [] in the following way.

  • Open the pokeman.service.ts, Import HttpClient, and add it as a dependency inside the constructor in the following.

  • After that add getAllPokemans() inside the service file and also call the API to get all the pokemon’s data in the following way.

Step 11. After that run and open the application inside the chrome browser by using localhost:4200. You can be able to see the redux tab inside the chrome browser.

Step 12. Open the pokeman.actions.ts, and add the below code to call the get all pokemon’s action.

Step 13. Open the pokeman.state.ts, in this file, we will create a state object and update the state object based on action. Also, we will add the selectors to get the data from the state.

  • Create a Pokeman state interface and add the pikeman's, totalCount inside the interface in the following way.
export interface POKEMAN_STATE_MODEL{  
    pokemans: any,  
    tatalCount: number  
}
  • Create PokemanState class, import state from @ngxs/store” and create state object for pokemans and also add default values, add @Injectable () on the top of PokemanState in the following way.
@State<any>({  
    name : 'pokemans',  
    defaults: {  
        pokemans: [ ],  
        tatalCount: 0  
    }  
})  

@Injectable()  
export class PokemanState{  
    constructor(){}  
}
  • The overall file of PokemanState is.

  • After that, Update the PokemanState inside app.module.ts in the following way.

After the above points are done, just open the application inside the browser window, you can see the state inside the chrome redux tab.

Step 14. Import the Pokeman service inside pokeman.state.ts and add it as a dependency inside the constructor.

Step 15. Open the pokeman.state.ts file and add the public getPokemans() method and add the @Action on the top of the method it indicates the method is called automatically when action is dispatched.

Step 16. Open pokeman.state.ts, Call the Pokeman Service getAllPokemans() method to get the pokemon’s data from the getPokemans method, After getting a response from the API, store the data inside the state by using the setState method.

Step 17. To get the updated data from the store, we need to write the static method i.e., pokemon, and add @Selector on the top of the method. In that way, the method behaves like a selector. Same way, add the totalCount to get the updated total count of pokemans from the store.

Step 18. After everything is done, please do npm install and ng serve. If you found any errors, please check all the points if no errors ignore this step.

Step 19. Oops, we have not added any code at the component level, if add then only we can be able to see the data inside the browser window.

  • Open app.component.ts and import store and add it as a dependency inside the constructor.

  • Import the GetAllPokemans actions from pokeman.actions.ts and dispatch the action by using the store.dispatch either from the constructor or ngOnInit.

  • After that check, the browser dev tools-> redux tab the pokeman data is there or not.

Step 20. We have completed the dispatch action in app.component.ts. After that, we need to get the data from the store.

  • Import PokemanState and Create the variable pokemans$. Assign the value to the pokemans$ after dispatching the action in the following way.

  • Create variable pokemanCount$, Import the Select from @ngxs/store, and add that on the top of the pokemanCount$ variable in that way the variable gets the data from the store.

Step 21. Add the below HTML code inside app.component.html to display the pokemon’s data inside the UI.

<div class="container mt-3">  
  <h3 class="mt-3 p-2 bg-primary text-white">List of pokemans <span *ngIf="pokemanCount$ | async as pokemanCount">( {{pokemanCount}} )</span></h3>  
  <ul class="list-group" *ngIf="pokemans$ | async as pokemans" style="height: 500px;overflow-y: auto;">  
    <li class="list-group-item" *ngFor="let pokeman of pokemans">  
      {{pokeman.name | titlecase }}  
    </li>  
  </ul>  
</div>

To see the changes in the browser, please run the application and check the changes. If you found any errors, please check all points once again.

Step 22. Am able to see the changes inside the browser but am not able to see the line item highlighted after clicks. For that add the below code.

  • Create a selectedPokeman variable and give the value as -1 and also create the selectPokeman method to update the selectedPokeman variable value.

  • After that app.component.html and add the click event to update the selectedPokeman, ngClass to highlight the line item.
<div class="container mt-3">  
  <h3 class="mt-3 p-2 bg-primary text-white">List of pokemans <span *ngIf="pokemanCount$ | async as pokemanCount">( {{pokemanCount}} )</span></h3>  
  <ul class="list-group" *ngIf="pokemans$ | async as pokemans" style="height: 500px;overflow-y: auto;">  
    <li class="list-group-item" \[ngClass\]="selectedPokeman===pokeman.url ? 'active' : ''" (click)="selectedPokeman = pokeman.url" *ngFor="let pokeman of pokemans">  
      {{pokeman.name | titlecase }}  
    </li>  
  </ul>  
</div>

Hmm, finally all the steps are done. Am able to see the changes inside the browser.

ngxs output.gif

Source:

Frontend: angular-ngxs-simple-example

Thanks for reading my article, Please share your feedback, claps, and comments. In that way, it will be helped me to improve my articles in the future. Please share my story with your near and dear

For Support