Defining NgRx Effects
Learn how to define NgRx Effects in our course project.
We'll cover the following...
- Introduction
- Defining an NgRx effect
- Defining the ProductsEffects
- Injecting the actions$ observable
- Injecting the ProductsService
- Defining an effect using createEffect()
- Subscribing to the actions$ observable
- Filtering loadProductsAction
- Fetching data from the server
- Handling the success response
- Registering the ProductsEffects
- Handling error response
Introduction
We’ve already removed the data that is retrieving logic from the ProductsComponent
. Let’s define an effect that interacts with the ProductsService
class to fetch data from the server.
Defining an NgRx effect
We can define an NgRx effect in an Angular application by following some steps. Let’s see them in detail below.
Defining the ProductsEffects
Inside the src/app/products/state
folder, let’s create a new file named products.effects.ts
. In this file, we’ll define all of the effects of ProductsModule
. Now, let’s define the ProductsEffects
class and its constructor()
function in lines 4–8. Since NgRx Effects are like an Angular service, let’s add an @Injectable()
decorator in lines 1–3.
Although Angular services and effects are defined similarly, the main distinction is that Angular services can be injected anywhere in our application. However, NgRx Effects cannot be injected into other portions of the application. It is exclusively intended for usage by the @ngrx/effects
library.
import { Injectable } from "@angular/core";@Injectable()export class ProductsEffects {constructor() { }}
Injecting the actions$
observable
In the constructor()
function, let’s inject the actions$
observable from the ...