Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chain Actions in an Effect in @ngrx

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!

like image 304
Tanmay Avatar asked Aug 13 '18 04:08

Tanmay


People also ask

What is ngrx effects?

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.

What is ofType in RXJS?

'ofType' filters an Observable of Actions into an observable of the actions whose type strings are passed to it.

What is @effect in angular?

} ​@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.


1 Answers

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')),
  ])
);
like image 148
timdeschryver Avatar answered Oct 21 '22 19:10

timdeschryver