Understanding Angular NgRx: Explaining Effects, Reducers, Actions, and Stores with Practical Examples

Posted by


Angular NGRX is a powerful state management tool that allows developers to manage state in their Angular applications in a more efficient and organized way. One of the key components of NGRX is the use of effects, reducers, actions, and stores. In this masterclass, we will explore each of these concepts in detail, and provide practical examples to help you understand how they work in a real-world application.

Effects:

Effects are responsible for handling side effects in your application, such as HTTP requests, localStorage operations, or any other asynchronous operations. Effects allow you to separate your business logic from the side effects, making your code more maintainable and testable.

To create an effect, you need to define an observable that listens for a specific action and performs the side effect when that action is dispatched. Here’s an example of how to create an effect in NGRX:

@Effect()
loadData$ = this.actions$.pipe(
  ofType(ActionTypes.LOAD_DATA),
  switchMap(() => this.dataService.loadData()),
  map(data => ({ type: ActionTypes.LOAD_DATA_SUCCESS, payload: data })),
  catchError(error => of({ type: ActionTypes.LOAD_DATA_ERROR, payload: error }))
);

In this example, we define an effect that listens for the LOAD_DATA action, then calls a loadData method in a dataService, and dispatches either a LOAD_DATA_SUCCESS action with the data as payload, or a LOAD_DATA_ERROR action with the error as payload if an error occurs.

Reducers:

Reducers are responsible for updating the state of your application in response to actions. Reducers are pure functions that take the current state and an action as arguments, and return a new state based on the action. Reducers should not have any side effects, and should always return a new state object without mutating the original state.

Here’s an example of how to create a reducer in NGRX:

export const reducer = createReducer(
  initialState,
  on(ActionTypes.LOAD_DATA_SUCCESS, (state, { payload }) => ({ ...state, data: payload })),
  on(ActionTypes.LOAD_DATA_ERROR, (state, { payload }) => ({ ...state, error: payload }))
);

In this example, we define a reducer that listens for the LOAD_DATA_SUCCESS and LOAD_DATA_ERROR actions, and updates the state with the data or error payload accordingly.

Actions:

Actions are plain objects that represent an intent to change the state of your application. Actions are typically dispatched by components, services, or effects, and are consumed by reducers to update the state. Actions have a type property that defines the type of action, and an optional payload property that contains additional data needed to update the state.

Here’s an example of how to define an action in NGRX:

export const loadData = createAction(ActionTypes.LOAD_DATA);

In this example, we define an action called LOAD_DATA that does not have a payload. Actions can also have a payload that is passed as an argument to the createAction function.

Stores:

Stores are responsible for holding the state of your application, and providing an interface to access and update that state. Stores in NGRX are implemented using the @ngrx/store package, which provides a Store class to create and manage the state of your application.

Here’s an example of how to create a store in NGRX:

export interface AppState {
  data: any;
  error: any;
}

export const initialState: AppState = {
  data: null,
  error: null
};

export const store = createStore(reducer, initialState);

In this example, we define an interface AppState that represents the shape of the state, an initial state object, and create a store using the createStore function with the reducer and initial state.

In conclusion, NGRX is a powerful state management tool that allows you to manage state in your Angular applications in a more efficient and organized way. By using effects, reducers, actions, and stores, you can build complex applications with predictable and maintainable state management. I hope this masterclass has helped you understand these concepts better, and provided you with practical examples to get you started with NGRX in your own projects. Happy coding!

0 0 votes
Article Rating

Leave a Reply

26 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@guilhermelacerda3908
2 hours ago

Maravilhoso!

⭐⭐⭐⭐⭐

@pauloeduardo1461
2 hours ago

Igual o lixo do Redux no ambiente React.
Dá pra gerenciar o estado da aplicação com o uso de serviços de forma muito mais limpa e intuitiva com Angular.

@luizfernando-tu5si
2 hours ago

dei uma risada honesta no "fodse uq acontece por debaixo dos panos" kkkkkk

@KallyFire1
2 hours ago

Achei legal, parece muito o redux do react kkk, foi até tranquilo de entender por conta disso, obg fessor 🎉

@gabrielbeirigo4416
2 hours ago

Muito interessante a aula para o Angular, quanto ao React, consigo tbm tratar coisas simples com Context Api, em vez de usar redux, que também deixa tudo mais complexo.

@CapyDev404
2 hours ago

Cara, difícil dar um feedback falando tudo que a gente quer dizer de uma aula incrível como essa, mas vou tentar resumir. Ficou bem didático: Você usou um exemplo simples, explicou o conceito/fluxo (do Redux/NgRx) da forma correta e fez algo que muita gente não faz (não porque não querem, mas por tentar ensinar algo de boa vontade apesar de não dominarem o assunto, oque vale é a intenção). No mais, fiquei surpreso de saber que era a quinta gravação sendo que mostrou um carisma e boa disposição/vontade do início ao fim da aula. Sou muito grato por essa jóia que você produziu, tenho certeza que ajudou muita gente. O like é o mínimo e a inscrição tá feita. Oque eu precisar aprender em vídeo (angular), vou ter seu canal como referência. Valeeeeu.

@joseclaudio6706
2 hours ago

Parabéns pela sua arte, á dias que estava a procura de um conteúdo com essa qualidade, sou DEV java e atualmente peguei um projeto com Angular que usar o NGRX. Com essa aula agora posso ficar mais tranquilo e seguir com meu trabalho.

@Um_Zuca_Dev_Na_Ilha_da_Madeira
2 hours ago

Cara seu canal é uma benção parabéns pela aula. É como vc disse eu tb não usaria, o Angular é muito complexo e este bagulho piorou o Angular, creio q isto só aumenta o custo de um projeto, sem muitos reais retornos de produtividade. Se um dia eu chegar a ser um Team Leader, eu jamais implementaria o NgRX algo assim.

@Um_Zuca_Dev_Na_Ilha_da_Madeira
2 hours ago

Cristian se usa -se em somente em aplicações serveless? Pois estes Status etc o Backend já nos fornece nas requisições HTTP, não fica algo retundante?

@brunoc.a.gaudino6150
2 hours ago

Excelente aula, embora eu já conheça o Angular como você disse vai um tempo para entender o NGRx! Parabéns 👏🏽

@brunoc.a.gaudino6150
2 hours ago

Excelente aula, embora eu já conheça o Angular como você disse vai um tempo para entender o NGRx! Parabéns 👏🏽

@vkRenan
2 hours ago

é uma macaquice da porra, pra chegar no mesmo resultado usando service e component.

@lindermannla
2 hours ago

Cristian quando der gera um conteúdo do NgRX/Signals plz!

@dev.danstone
2 hours ago

Vc é o cara mano

@marcosjesus07
2 hours ago

Estou aprendendo angular e por saber Vue e ter uma ampla xp com Vue, venho tendo uma facilidade, mas estou vendo que Angular a curva realmente é longa, por conta da Programação Reativa, questão das propriedades que ela contém, tendo essa visão ai essa parte de state manager se torna simples, e outras coisas do framework em si, o que está pegando mesmo é a questão do Rx e o não uso de promisse com Rx e sim observables.

@djrandomoficial4901
2 hours ago

Os indianos devem adorar essa porra kkk

@djrandomoficial4901
2 hours ago

vou aplicar na prox sprint do App Itau, salvou d+ braboooo

@chico3870
2 hours ago

didática sensacional!

@SilvairLeiteSoares
2 hours ago

Até chegar nos effects, tava indo bem. Dai em diante, não entendi mais nada 😆😆

@josevicentedesousa
2 hours ago

Espetáculo Cristian. C não tem ideia da importância dos seus vídeos pra gente que esta iniciando. Obrigado!!

26
0
Would love your thoughts, please comment.x
()
x