0
0
Angularframework~5 mins

Effect for side effects in Angular

Choose your learning style9 modes available
Introduction

Effects let your Angular app do extra work when something changes, like fetching data or saving info. They help keep your app organized by handling these side tasks outside your main code.

When you want to load data from a server after a user clicks a button.
When you need to save user input to a database without blocking the screen.
When you want to show a message after an action completes, like a success alert.
When you need to react to changes in your app state by triggering other actions.
Syntax
Angular
import { effect, inject } from '@angular/core';
import { SomeService } from './some.service';

const someEffect = effect(() => {
  const service = inject(SomeService);
  service.doSomething();
});

Use effect to run code that reacts to changes or triggers side tasks.

Use inject() inside effects to get services or dependencies.

Examples
This effect logs a message whenever it runs.
Angular
import { effect, inject } from '@angular/core';
import { LoggerService } from './logger.service';

const logEffect = effect(() => {
  const logger = inject(LoggerService);
  logger.log('Effect ran');
});
This effect calls a method to load data, for example from a server.
Angular
import { effect, inject } from '@angular/core';
import { DataService } from './data.service';

const fetchEffect = effect(() => {
  const dataService = inject(DataService);
  dataService.loadData();
});
Sample Program

This Angular component has a button. When clicked, it sets a signal to true. The effect watches this signal and calls the data service to load data, printing a message to the console.

Angular
import { Component, effect, inject, signal, Injectable } from '@angular/core';

@Injectable()
class DataService {
  loadData() {
    console.log('Loading data...');
  }
}

@Component({
  selector: 'app-root',
  standalone: true,
  providers: [DataService],
  template: `<button (click)="load()">Load Data</button>`,
})
export class AppComponent {
  private dataService = inject(DataService);
  private loadSignal = signal(false);

  constructor() {
    effect(() => {
      if (this.loadSignal()) {
        this.dataService.loadData();
      }
    });
  }

  load() {
    this.loadSignal.set(true);
  }
}
OutputSuccess
Important Notes

Effects run automatically when the signals or dependencies they watch change.

Keep side effects like API calls or logging inside effects to keep your components clean.

Summary

Effects help run extra code when something changes in your app.

Use effects for tasks like loading data or logging.

They keep side tasks separate from your main app logic.