Search⌘ K
AI Features

Isolating Side Effects from Components

Explore how to isolate side effects from Angular components by using NgRx Effects. This lesson guides you through removing service calls from components, dispatching actions to trigger effects, and updating the store for better maintainability and testability of your application.

Introduction

The purpose of using NgRx Effects is to remove side effects from the Angular components. In our src/app/products/products.component.ts file, we’re using the ProductsService class to fetch product data from the server. In this lesson, we’ll refactor the ProductsComponent to remove the side effects.

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 the products data from the server

Removing side effects

Let’s remove the ProductsService-related code from the ...