Performance: Effects for side effects
This affects the responsiveness and smoothness of user interactions by managing side effects outside the component rendering cycle.
Jump into concepts and practice - no test required
readonly loadDataEffect = effect(() => { this.http.get('/api/data').subscribe(data => { this.data.set(data); this.logService.log('Data loaded'); }); });this.http.get('/api/data').subscribe(data => { this.data = data; this.logService.log('Data loaded'); });
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Direct subscription in component | Multiple DOM updates | Multiple reflows per update | Higher paint cost due to frequent updates | [X] Bad |
| Angular Effects for side effects | Minimal DOM updates triggered | Single or no reflows per effect | Lower paint cost with batched updates | [OK] Good |
Effects in Angular applications?createEffect function?createEffect function expects a function returning an observable, so it should be () => this.actions$.pipe(...).switchMap is correct for side effects that return new observables. const loadData$ = createEffect(() => this.actions$.pipe(ofType(load), switchMap(() => fetchData()))); uses this correctly.loadData$ = createEffect(() => this.actions$.pipe(
ofType(loadData),
switchMap(() => this.api.getData()),
map(data => loadDataSuccess({ data })),
catchError(() => of(loadDataFailure()))
));loadData action is dispatched?loadData action is dispatched, the effect listens and triggers the API call via switchMap.map dispatches loadDataSuccess with data; on error, catchError dispatches loadDataFailure.loadDataSuccess action is dispatched -> Option DsaveData$ = createEffect(() => this.actions$.pipe(
ofType(saveData),
switchMap(action => this.api.save(action.payload)),
map(() => saveDataSuccess()),
catchError(error => saveDataFailure({ error }))
));catchError operator must return an observable, but here it returns an action object directly.of() makes it an observable, fixing the error.catchError operator should return an observable -> Option Alogin actions, calls an API to authenticate, and then dispatches either loginSuccess or loginFailure. Additionally, you want to log every login attempt regardless of success or failure. Which approach correctly implements this using Angular Effects?dispatch: false.loginSuccess or loginFailure accordingly.