seif hassan
Posted on June 27, 2023
Discover the simplicity of handling the state of your #Angular application through #NGXS and grasp the knowledge of integrating NGXS.
State Management
State Management involves utilizing a Design Pattern to effectively utilize a single data source across various components of an application. This approach offers advantages like data reliability, simplified code maintenance, and more.
NGXS
NGXS is an Angular-centric State Management Pattern that serves as a centralized data source for your application's state, offering straightforward implementation. In my view, NGXS is easier to adopt compared to NGRX
In NGXS, there are four key concepts to incorporate:
Store
The store in NGXS acts as a central state manager, allowing for action dispatching and enabling the selection of specific data slices from the global state.
Actions
Actions in NGXS represent specific tasks or operations that can be performed to achieve desired outcomes. For instance, we can dispatch a "Get Books" action to retrieve books. When defining actions, it is necessary to specify a type that describes the nature of the action.
State
States in NGXS are responsible for defining the container that holds the application's state. It is possible to have various fundamental states that are commonly utilized in applications, such as:
1.✌️ An initial state
2.🔃 A loading state
3.👎 An error state
4.☑️ A success state
Select
Selects in NGXS are functions that enable us to retrieve specific data from our store. There are two approaches to perform this:
Using decorators:
export class NameYourComponent {
@Select(TodosState) todos$: Observable<Todos[]>;
}
Using store selection functions:
export class NameYourComponent {
todos$: Observable<Todos[]>;
constructor(private _store: Store) {
this.todos$ = this._store.select(state => state.todos.todos);
}
}
With a fundamental understanding of State Management, NGXS, and its underlying concepts, we are now ready to apply it in a practical application!
To begin, install the necessary dependencies by following these steps:
(NGXS): Install on the project:
npm i @ngxs/store
Helper plugins
- devtools plugin
npm i @ngxs/devtools-plugin
To Use it Install this Extension
https://chrome.google.com/webstore/detail/redux-devtools/lmhkpmbekcpmknklioeibfkpmmfibljd?hl=pt
- logger plugin
npm install @ngxs/logger-plugin --save
Or if you are using yarn:
yarn add @ngxs/logger-plugin
Now, we just have to add the module to our imports in the @NgModule of our application like this:
import {NgxsLoggerPluginModule} from '@ngxs/logger-plugin';
@NgModule({
imports: [
...
NgxsLoggerPluginModule.forRoot({
disabled: environment.production
}),
],
...
})
export class AppModule { }
Posted on June 27, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.