← Back to Angular, page 4

angular-0071 · Medium mid

What are NgRx Effects, how do you write a functional effect that loads data, and how do you choose between switchMap, exhaustMap and concatMap in effects?

An effect listens to dispatched actions, performs a side effect such as an HTTP call, and dispatches new actions with the result. A functional effect is written with createEffect and inject. Effects use flattening operators, so the choice of switchMap, exhaustMap or concatMap decides how overlapping requests behave.

Full answer

Reducers must be pure, so anything else (HTTP, storage, timers, navigation) lives in effects. An effect is an Observable of actions in, actions out.

ts
export const loadCourses = createEffect(
  (actions$ = inject(Actions), api = inject(CourseApi)) =>
    actions$.pipe(
      ofType(CoursesPageActions.opened),
      exhaustMap(() =>
        api.list().pipe(
          map((courses) => CoursesApiActions.loadSuccess({ courses })),
          catchError((error) => of(CoursesApiActions.loadFailure({ error: String(error) }))),
        ),
      ),
    ),
  { functional: true },
);

Points about this code:

  • Actions is the stream of all dispatched actions. ofType filters it.
  • Default parameters with inject() give the effect its dependencies in a plain function. Class-based effects (@Injectable with createEffect fields) are the older style and still common.
  • The catchError is inside the inner Observable, so one failure does not kill the effect stream. This is the most common effect bug.
  • Effects are registered with provideEffects({ loadCourses }) (functional) or provideEffects(MyEffects) (class).
  • Effects that only do a side effect without dispatching, such as logging, use { dispatch: false }.

Choosing the flattening operator:

  • switchMap: latest wins, for reads such as search. It cancels the older request.
  • exhaustMap: ignore new triggers while one is running. Good for loading on button press, login, and refresh clicks.
  • concatMap: queue in order. Good for writes where order matters.
  • mergeMap: parallel, with no order guarantee. Good for independent writes.

Testing: use provideMockActions(() => actions$) from @ngrx/effects/testing, feed an action, and check the emitted result. No store is needed.

Keep effects small and the actions meaningful. An effect that dispatches an action that triggers another effect that dispatches another is hard to follow.

typescript
import { Injectable, inject } from '@angular/core';
import { Actions, createEffect, ofType, provideEffects } from '@ngrx/effects';
import { createActionGroup, emptyProps, props, provideStore } from '@ngrx/store';
import { ApplicationConfig } from '@angular/core';
import { Observable, catchError, exhaustMap, map, of } from 'rxjs';

export interface Course {
  id: number;
  title: string;
}

export const CoursesActions = createActionGroup({
  source: 'Courses',
  events: {
    Opened: emptyProps(),
    'Load Success': props<{ courses: Course[] }>(),
    'Load Failure': props<{ error: string }>(),
  },
});

@Injectable({ providedIn: 'root' })
export class CourseApi {
  list(): Observable<Course[]> {
    return of([{ id: 1, title: 'Angular' }]);
  }
}

export const loadCourses = createEffect(
  (actions$ = inject(Actions), api = inject(CourseApi)) =>
    actions$.pipe(
      ofType(CoursesActions.opened),
      exhaustMap(() =>
        api.list().pipe(
          map((courses) => CoursesActions.loadSuccess({ courses })),
          catchError((error: unknown) => of(CoursesActions.loadFailure({ error: String(error) }))),
        ),
      ),
    ),
  { functional: true },
);

export const logFailures = createEffect(
  (actions$ = inject(Actions)) =>
    actions$.pipe(
      ofType(CoursesActions.loadFailure),
      map(({ error }) => console.error('Load failed', error)),
    ),
  { functional: true, dispatch: false },
);

export const appConfig: ApplicationConfig = {
  providers: [provideStore(), provideEffects({ loadCourses, logFailures })],
};

Angular 20.3 with NgRx 20.1, type-checked. A Karma spec in headless Chrome runs the `loadCourses` effect with `provideMockActions` for both the success path and an API error that becomes a failure action. The API service is a fake with fixed data.

Key points

  • Effects turn actions into side effects and new actions. Reducers stay pure.
  • Put `catchError` inside the inner Observable.
  • Pick `switchMap`, `exhaustMap`, `concatMap`, or `mergeMap` by how overlap should behave.
  • Test with `provideMockActions`. Register with `provideEffects`.

Common mistakes

  • Putting `catchError` on the outer stream, which stops the effect after the first error.
  • Using `switchMap` for save operations, which can cancel a write.
  • Chains of effects that trigger each other, which are hard to debug.

Follow-ups

  • Why does an effect need `catchError` on the inner stream?
  • How would you run an effect on application start?
  • How do you test an effect without a store?

Tips

  • Show the inner catchError placement first. It proves understanding.
  • Tie operator choice to the user action (read, button press, write).
  • Mention functional effects as the current style and class effects as legacy.

Evaluation rubric

  • Writes a functional effect with the correct structure.
  • Chooses flattening operators with reasons.
  • Knows how to test effects.