Security News
Highlights from the 2024 Rails Community Survey
A record 2,709 developers participated in the 2024 Ruby on Rails Community Survey, revealing key tools, practices, and trends shaping the Rails ecosystem.
@ngrx/effects
Advanced tools
@ngrx/effects is a library for managing side effects in Angular applications using the Redux pattern. It allows you to isolate side effects from your components and services, making your code more predictable and easier to test.
Handling Side Effects
This code demonstrates how to handle side effects using @ngrx/effects. The `loadItems$` effect listens for the `loadItems` action, calls a service to fetch data, and then dispatches either a success or failure action based on the result.
import { Injectable } from '@angular/core';
import { Actions, createEffect, ofType } from '@ngrx/effects';
import { of } from 'rxjs';
import { catchError, map, mergeMap } from 'rxjs/operators';
import { MyService } from './my-service';
import * as MyActions from './my-actions';
@Injectable()
export class MyEffects {
loadItems$ = createEffect(() => this.actions$.pipe(
ofType(MyActions.loadItems),
mergeMap(() => this.myService.getAll().pipe(
map(items => MyActions.loadItemsSuccess({ items })),
catchError(() => of(MyActions.loadItemsFailure()))
))
));
constructor(
private actions$: Actions,
private myService: MyService
) {}
}
Combining Multiple Effects
This code demonstrates how to combine multiple effects in a single class. The `loadItems$` effect handles loading items, while the `updateItem$` effect handles updating an item. Both effects listen for their respective actions and call the appropriate service methods.
import { Injectable } from '@angular/core';
import { Actions, createEffect, ofType } from '@ngrx/effects';
import { of } from 'rxjs';
import { catchError, map, mergeMap } from 'rxjs/operators';
import { MyService } from './my-service';
import * as MyActions from './my-actions';
@Injectable()
export class MyEffects {
loadItems$ = createEffect(() => this.actions$.pipe(
ofType(MyActions.loadItems),
mergeMap(() => this.myService.getAll().pipe(
map(items => MyActions.loadItemsSuccess({ items })),
catchError(() => of(MyActions.loadItemsFailure()))
))
));
updateItem$ = createEffect(() => this.actions$.pipe(
ofType(MyActions.updateItem),
mergeMap(action => this.myService.update(action.item).pipe(
map(() => MyActions.updateItemSuccess({ item: action.item })),
catchError(() => of(MyActions.updateItemFailure()))
))
));
constructor(
private actions$: Actions,
private myService: MyService
) {}
}
Error Handling
This code demonstrates how to handle errors in effects. The `loadItems$` effect catches any errors that occur during the service call and dispatches a `loadItemsFailure` action with the error information.
import { Injectable } from '@angular/core';
import { Actions, createEffect, ofType } from '@ngrx/effects';
import { of } from 'rxjs';
import { catchError, map, mergeMap } from 'rxjs/operators';
import { MyService } from './my-service';
import * as MyActions from './my-actions';
@Injectable()
export class MyEffects {
loadItems$ = createEffect(() => this.actions$.pipe(
ofType(MyActions.loadItems),
mergeMap(() => this.myService.getAll().pipe(
map(items => MyActions.loadItemsSuccess({ items })),
catchError(error => of(MyActions.loadItemsFailure({ error })))
))
));
constructor(
private actions$: Actions,
private myService: MyService
) {}
}
redux-saga is a library that aims to make side effects (e.g., asynchronous actions like data fetching) easier and more manageable in Redux applications. It uses generator functions to handle side effects, which can make the code more readable and easier to test compared to @ngrx/effects.
redux-thunk is a middleware that allows you to write action creators that return a function instead of an action. This function can then perform asynchronous dispatches. While simpler than @ngrx/effects, it can become harder to manage as the complexity of side effects grows.
MobX is a state management library that makes it simple to connect the reactive data of your application with the UI. Unlike @ngrx/effects, MobX uses observables to manage state and side effects, which can be more intuitive for some developers.
To install @ngrx/effects from npm:
npm install @ngrx/effects --save
https://github.com/ngrx/example-app
In @ngrx/effects, effects are sources of actions. You use the @Effect()
decorator to hint which observables on a service are action sources, and @ngrx/effects automatically connects your action sources to your store
To help you compose new action sources, @ngrx/effects exports a StateUpdates
observable service that emits a StateUpdate
object, containing the current state and dispatched action, for each state update.
Note: Even if there are no changes in your state, every action will cause state to update!
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Action } from '@ngrx/store';
import { StateUpdates, Effect } from '@ngrx/effects'
@Injectable()
export class AuthEffects {
constructor(private http: Http, private updates$: StateUpdates<any>) { }
@Effect() login$ = this.updates$
// Listen for the 'LOGIN' action
.whenAction('LOGIN')
// Map the payload into JSON to use as the request body
.map(update => JSON.stringify(update.action.payload))
.switchMap(payload => this.http.post('/auth', payload)
// If successful, dispatch success action with result
.map(res => ({ type: 'LOGIN_SUCCESS', payload: res.json() }))
// If request fails, dispatch failed action
.catch(() => Observable.of({ type: 'LOGIN_FAILED' }));
);
}
import { runEffects } from '@ngrx/effects';
bootstrap(App, [
provideStore(reducer),
runEffects(AuthEffects)
]);
The @Effect()
decorator provides metadata to hint which observables on a class should be connected to Store
. If you want to dynamically run an effect inject the effect class and subscribe the effect to Store
manually:
@Injectable()
export class AuthEffects {
@Effect() login$ = this.updates$
.whenAction('LOGIN')
.mergeMap(...)
}
@Component({
providers: [
AuthEffects
]
})
export class SomeCmp {
subscription: Subscription;
constructor(store: Store<State>, authEffects: AuthEffects) {
this.subscription = authEffects.login$.subscribe(store);
}
}
Unsubscribe to stop the effect:
ngOnDestroy() {
this.subscription.unsubscribe();
}
If you don't want to connect each source manually, you can use the mergeEffects()
helper function to automatically merge all decorated effects across any number of effect services:
import { OpaqueToken, Inject } from '@angular/core';
import { mergeEffects } from '@ngrx/effects';
const EFFECTS = new OpaqueToken('Effects');
@Component({
providers: [
provide(EFFECTS, { multi: true, useClass: AuthEffects }),
provide(EFFECTS, { multi: true, useClass: AccountEffects }),
provide(EFFECTS, { multi: true, useClass: UserEffects })
]
})
export class SomeCmp {
constructor(@Inject(EFFECTS) effects: any[], store: Store<State>) {
mergeEffects(effects).subscribe(store);
}
}
To test your effects mock out your effect's dependencies and use the MockStateUpdates
service to send actions and state changes to your effect:
import {
MOCK_EFFECTS_PROVIDERS,
MockStateUpdates
} from '@ngrx/effects/testing';
describe('Auth Effects', function() {
let auth: AuthEffects;
let updates$: MockStateUpdates;
beforeEach(function() {
const injector = ReflectiveInjector.resolveAndCreate([
AuthEffects,
MOCK_EFFECTS_PROVIDERS,
// Mock out other dependencies (like Http) here
]);
auth = injector.get(AuthEffects);
updates$ = injector.get(MockStateUpdates);
});
it('should respond in a certain way', function() {
// Add an action in the updates queue
updates$.sendAction({ type: 'LOGIN', payload: { ... } });
auth.login$.subscribe(function(action) {
/* assert here */
});
});
});
You can use MockStateUpdates@sendAction(action)
to send an action with an empty state, MockStateUpdates@sendState(state)
to send a state change with an empty action, and MockStateUpdates@send(state, action)
to send both a state change and an action. Note that MockStateUpdates
is a replay subject with an infinite buffer size letting you queue up multiple actions / state changes to be sent to your effect.
@ngrx/effects is heavily inspired by store-saga making it easy to translate sagas into effects.
In store-saga, an iterable$
observable containing state/action pairs was provided to your saga factory function. Typically you would use the filter
operator and the whenAction
helper to listen for specific actions to occur. In @ngrx/effects, an observable named StateUpdates
offers similar functionality and can be injected into an effect class. To listen to specific actions, @ngrx/effects includes a special whenAction
operator on the StateUpdates
observable.
Before:
// ... other needed imports here ...
import { createSaga, whenAction, toPayload } from 'store-saga';
const login$ = createSaga(function(http: Http) {
return iterable$ => iterable$
.filter(whenAction('LOGIN'))
.map(iteration => JSON.stringify(iteration.action.payload))
.mergeMap(body => http.post('/auth', body)
.map(res => ({
type: 'LOGIN_SUCCESS',
payload: res.json()
}))
.catch(err => Observable.of({
type: 'LOGIN_ERROR',
payload: err.json()
}))
);
}, [ Http ]);
After:
// ... other needed imports here ...
import { Effect, toPayload, StateUpdates } from '@ngrx/effects';
@Injectable()
export class AuthEffects {
constructor(private http: Http, private updates$: StateUpdates<State>) { }
@Effect() login$ = this.updates$
.whenAction('LOGIN')
.map(update => JSON.stringify(update.action.payload))
.mergeMap(body => this.http.post('/auth', body)
.map(res => ({
type: 'LOGIN_SUCCESS',
payload: res.json()
}))
.catch(err => Observable.of({
type: 'LOGIN_ERROR',
payload: err.json()
}))
);
}
FAQs
Side effect model for @ngrx/store
The npm package @ngrx/effects receives a total of 343,361 weekly downloads. As such, @ngrx/effects popularity was classified as popular.
We found that @ngrx/effects demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 4 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
A record 2,709 developers participated in the 2024 Ruby on Rails Community Survey, revealing key tools, practices, and trends shaping the Rails ecosystem.
Security News
In 2023, data breaches surged 78% from zero-day and supply chain attacks, but developers are still buried under alerts that are unable to prevent these threats.
Security News
Solo open source maintainers face burnout and security challenges, with 60% unpaid and 60% considering quitting.