Angular › NgRx State Management
How do NgRx Effects let you handle asynchronous operations, like an API call, in response to a dispatched action?
AdvancedAnswer
An Effect listens for a specific action, performs an asynchronous operation like an HTTP request, and then dispatches a new action once that operation completes, keeping asynchronous side effects cleanly separated from the pure, synchronous reducer functions that update the actual state.
loadUsers$ = createEffect(() =>
this.actions$.pipe(
ofType(loadUsers),
mergeMap(() => this.userService.getUsers().pipe(
map((users) => loadUsersSuccess({ users })),
catchError((error) => of(loadUsersFailure({ error })))
))
)
);Real-world example A user management page dispatches a loadUsers action, triggering an Effect that fetches the actual data from the server and dispatches a success action with the results, keeping the reducer itself completely free of any asynchronous logic.