Search⌘ K

Introduction to NgRx Effects

Explore how NgRx Effects handle side effects in Angular by separating service calls from components. Learn the flow of actions through reducers and effects, enabling easier testing and clearer state management in your applications.

What are effects?

In general, the components of an Angular application perform side effects through services. In our course project, the ProductsComponent retrieves data from the server via the ProductsService as follows:

TypeScript 3.3.4
import { Component, OnInit } from '@angular/core';
import { ProductsService } from '../products.service';
import { Store } from '@ngrx/store';
import { getProductsAction } from './state/products.actions';
import { getProductsSelector } from './state/products.selectors';
import { AppState, Product } from '../app.interfaces';
@Component({
selector: 'app-products',
templateUrl: './products.component.html',
styleUrls: ['./products.component.scss'],
})
export class ProductsComponent implements OnInit {
products$ = this.store.select<Product[]>(getProductsSelector);
constructor(private store: Store<AppState>, private productsService: ProductsService) {}
ngOnInit() {
this.getProducts();
}
getProducts() {
this.productsService
.getProducts()
.subscribe((products: Product[]) => (this.store.dispatch(getProductsAction({ products }))));
}
}
Retrieving products data from the server

In large applications, a component may need to handle multiple services that may become difficult to maintain over time. To overcome this problem, ...