Skip to content

Instantly share code, notes, and snippets.

@hollygood
Last active January 25, 2019 14:31
Show Gist options
  • Save hollygood/680b8581d432a0089022ff06758991be to your computer and use it in GitHub Desktop.
Save hollygood/680b8581d432a0089022ff06758991be to your computer and use it in GitHub Desktop.
Some examples for ngrx effects
// One input, one output
@Effect()
firstAction$: Observable<Action> = this.action$.pipe(
ofType<firstAction>('FIRST_ACTION'),
mapTo(new SecondAction())
);
// Two inputs, one output
@Effect()
public dashboardLoadRequired$: Observable<Action> =
this.actions$.pipe(
ofType( 'SIGN_IN_SUCCESS', 'OPEN_DASHBOARD'),
mapTo( new LoadDashboardData() )
);
// One input, two outputs
@Effect()
public signInSuccess$: Observable<Action> = this.actions$.pipe(
ofType( 'SIGN_IN_SUCCESS' ),
concatMapTo([
new LoadDashboardData(),
new LoadChatHistory()
])
);
// One input, no outputs
@Effect({dispatch: false})
public signInSuccess$: Observable<Action> = this.actions$.pipe(
ofType( 'SIGN_IN_SUCCESS' ),
tap( () => this.router.navigate(['dashboard']) )
);
// Effect with calling the service
@Effect()
getCustomers$ = this.actions.pipe(
// filter out the actions, except '[Customers Page] Get'
ofType(CustomerActionTypes.Get),
switchMap(() =>
// call the service
this.service.get().pipe(
// return a Success action when everything went OK
map(customers => new GetCustomersSuccess(customers)),
// return a Failed action when something went wrong
catchError(error => of(new GetCustomersFailed(error))),
),
),
);
// Use selector inside the Effect, and filter out existing entity
@Effect()
getOrder = this.actions.pipe(
ofType<GetOrder>(ActionTypes.GetOrder),
withLatestFrom(this.store.pipe(select(getOrders))),
filter(([{payload}, orders]) => !!orders[payload.orderId])
mergeMap([{payload}] => {
...
})
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment