I am having some trouble chaining actions one after the other in an Effect that makes an HTTP-request.
Here's the Effect code:
export class UserEffects {
@Effect()
update$: Observable<Action> = this.actions$.ofType(user.USERCHANGE).pipe(
switchMap(data => this.authService.login(data['payload'])),
map(userInfo => new UserChangedAction(userInfo)),
tap(() => this.store.dispatch(
new LoginStateChangeAction(localStorage.getItem('token')))
)
);
constructor(private authService: AuthService, private actions$: Actions,
public store: Store<fromRoot.State>) {}
}
The problem is both the actions are being called simultaneously. The LoginStateChange action depends on UserChanged action to complete.
How can I achieve this?
Thanks!
NgRx Effects provides us with a way to isolate interactions, with the aforementioned services, from the components. Within Effects, we can manage various tasks ie. communication with the API, long-running tasks, and practically every other external interaction.
'ofType' filters an Observable of Actions into an observable of the actions whose type strings are passed to it.
} @ngrx/effects provides an Angular actions$ service (which is also an Observable ) to emit every action that has been dispatched by your application in a single stream. Its ofType() method can be used to filter the one or more actions we're interesting in before adding a side-effect.
You can return multiple actions as explained in Austin's post: Dispatching Multiple Actions from NGRX Effects
@Effect()
update$ = this.actions$.ofType(user.USERCHANGE).pipe(
switchMap(data => this.authService.login(data['payload'])),
switchMap(userInfo => [
new UserChangedAction(userInfo),
new LoginStateChangeAction(localStorage.getItem('token')),
])
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With