I need to dispatch multiple actions from an ngrx effect once an http request is successful.
There are several ways that seem to work and some that don't, I can't understand what the difference is.
@Effect()
loadUser = this.actions
.pipe(
ofType(campaignActions.type.LOAD_CAMPAIGN),
map((action: userActions.LoadUserAction) => action.payload),
switchMap((payload: { id: number }) =>
this.s.getUser(payload.id)
.pipe(
switchMap((data) => {
return from([
new userActions.LoadUserSuccessAction(),
new userActions.SomethingElseSuccessAction()
]);
}),
catchError(() => of(new userActions.LoadUserFailureAction()))
)
)
);
First of all, I can use switchMap or mergeMap. I believe the difference is that if this effect is triggered multiple times, any ongoing requests will be cancelled if I use switchMap and not if I use mergeMap.
In terms of dispatching multiple actions, all the following works:
- return [action1, action2]
- return from([action1, action2])
- return of(action1, action2)
The following doesn't work:
- return of([action1, action2]) --> Effect "UserEffects.loadUser" dispatched an invalid action: [object Object],[object Object]
What is the difference between all the first 3 options? What about mergeMap vs switchMap after the http request? Why doesn't the last option work?