Security News
GitHub Removes Malicious Pull Requests Targeting Open Source Repositories
GitHub removed 27 malicious pull requests attempting to inject harmful code across multiple open source repositories, in another round of low-effort attacks.
@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.
In @ngrx/effects, effects are simply 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 every time your state updates along with the action that caused the state update. Note that even if there are no changes in your state, every action will cause state to update.
For example, here's an AuthEffects service that describes a source of login actions:
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) { }
@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' }));
);
}
Then you run your effects during bootstrap:
import { runEffects } from '@ngrx/effects';
bootstrap(App, [
provideStore(reducer),
runEffects(AuthEffects)
]);
The @Effect()
provides metadata to hint which observables on a class should be connected to Store
. If you want to dynamically run an effect, simply 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);
}
}
To stop the effect, simply unsubscribe:
ngOnDestroy() {
this.subscription.unsubscribe();
}
If you don't want to connect each source manually, you can use the simple 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, { useClass: AuthEffects }),
provide(EFFECTS, { useClass: AccountEffects }),
provide(EFFECTS, { useClass: UserEffects })
]
})
export class SomeCmp {
constructor(@Inject(EFFECTS) effects: any[], store: Store<State>) {
mergeEffects(effects).subscribe(store);
}
}
To test your effects, simply 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:
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:
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 => 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 0 weekly downloads. As such, @ngrx/effects popularity was classified as not 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
GitHub removed 27 malicious pull requests attempting to inject harmful code across multiple open source repositories, in another round of low-effort attacks.
Security News
RubyGems.org has added a new "maintainer" role that allows for publishing new versions of gems. This new permission type is aimed at improving security for gem owners and the service overall.
Security News
Node.js will be enforcing stricter semver-major PR policies a month before major releases to enhance stability and ensure reliable release candidates.