12

I am new to ngrx and Redux style architecture and I am having problems understanding how I should chain actions / effects. One example is achieving basic functionality such as taking an action after a user logs in. My core struggle here is that the action to be taken after the user has logged in will vary depending upon the current state of the application - the user may be anywhere in the application when presented with a login prompt / page.

Any examples I have seen hardcode effects which will happen once the user has logged in. In my scenario this does not fit well as stated above I do not always want the same action to happen.

Here is some example code of a home page which includes a login component. In this scenario I would like the user to be redirected to '/buy' once they have logged in.

@Component(..)
export class HomePageComponent {
    constructor(private store: Store<any>) {
    }

    public onLoginSubmitted(username, password) {
        this.store.dispatch(new loginActions.Login({username, password}));
        // once this has happened successfully navigate to /buy    
    }

}

Example effect

@Injectable()
export class LoginEffects {

    ......     

    @Effect()
    login$ = this.actions$
        .ofType(loginActions.ActionTypes.LOGIN)
        .switchMap((data) => {
            return this.loginService.login(data.payload)
                .map(() => new loginActions.LoginSuccess({loggedIn: true, isLoggingIn: false}))
                .catch((error) => {
                    return of(new loginActions.LoginError({loggedIn: false, isLoggingIn: false}));
                });
        });
    ......
}

I have several thoughts on how you might solve this problem - but none of them feel right. These include

  • passing data with the login payload to determine an action to take next
  • writing lots of effects which upon LoginSuccess take action but are filtered at some higher level
  • write a component specific effect by listening to events on the store ( is this possible / bad practice ? )
  • reading data from the store about the current login status and acting upon this in the component. However this logic would run immediately, which may not have the desired effect

Can anyone point me down the right path / present examples of how this should be solved?

2
  • Could part of the payload be the redirectRoute, and then after login, the LoginSuccess effect would navigate based on where redirectRoute specifies. You would only have one loginSuccess action, but it could redirect to anywhere.
    – Adam
    Commented Feb 21, 2017 at 16:52
  • It could be - but this assumes that you will always want to redirect after login. This may not necessarily be the case, for example you may want to dismiss a modal
    – dannym
    Commented Feb 21, 2017 at 17:21

1 Answer 1

11

An effect can fire off multiple actions using mergeMap on an array of actions. What I would usually do is, pass in the additional actions that I would like the login effect to also dispatch.

@Component(..)
export class HomePageComponent {
    constructor(private store: Store<any>) { }

    public onLoginSubmitted(username, password) {
        this.store.dispatch(new loginActions.Login({
            username, 
            password, 
            onCompleteActions: [new loginActions.Redirect({ route: '/buy' })] }));
    }
}

The login effect would then dispatch any passed-in actions using mergeMap. You would still have to create an effect for each action, but now you can build more reusable actions, such as a redirect action.

@Injectable()
export class LoginEffects {

    ......     

    @Effect()
    login$ = this.actions$
        .ofType(loginActions.ActionTypes.LOGIN)
        .switchMap((data) => {
            let mappedActions = [new loginActions.LoginSuccess({loggedIn: true, isLoggingIn: false})];
            if (data.payload.onCompleteActions)
                mappedActions = mappedActions.concat(data.payload.onCompleteActions);

            return this.loginService.login(data.payload)
                .mergeMap(mappedActions)
                .catch((error) => {
                    return of(new loginActions.LoginError({loggedIn: false, isLoggingIn: false}));
                });
        });

    ......
}

What I like about this solution is that it is scalable into the future, since any actions can be passed in, and there's no switch or if-else tree to decide what to do. You can also pass in multiple actions, so there's no need to build a 'redirectAndCloseModal' action, you could pass in redirect as well as closeModal.

this.store.dispatch(new loginActions.Login({
    username, 
    password, 
    onCompleteActions: [new loginActions.Redirect({ route: '/buy' }), new modalActions.CloseModal()] }));

You can read a bit more about dispatching multiple Actions from one @Effect() at this github issue.

Edit: Regarding you comments, it's not just route changes that may make you want to stop the login, it could be anything, such as closing a modal, and there's no generic way to watch for that. You could add something to your store such as a runLoginActions boolean, and then read that data from your store after the login request comes back.

Then in your login$ effect, you could read that from the store to decide to run the additional actions or not.

@Effect()
login$: Observable<Action> = this.actions$
    .ofType(auth.actionTypes.LOGIN)
    .map((action: auth.LoginAction) => action.payload)
    .switchMap((user) => {
        let successAction = new loginActions.LoginSuccess({loggedIn: true, isLoggingIn: false});
        let mappedActions = [successAction];
        if (data.payload.onCompleteAction)
            mappedActions.push(data.payload.onCompleteAction);

        return this.authService.login(user.username, user.password)
            .withLatestFrom(this.store)
            .mergeMap(([result, store]) => store.runLoginActions ?
                [mappedActions] :
                [successAction]
            )
            .catch((err) => {
                try {
                    return of(new auth.NetworkFailureAction(err[0].code));
                } catch (e) {
                    throw `Array not in the expected format of [{ code: "", message: "" }]`;
                }
            });
    });

Note that in your reducer for loginSuccess, you should set your runLoginActions = true, and it should start as true by default, only to be turned off when a route is changed, or a component is destroyed.

Keep in mind this is a general solution, and you're going to need to add the actions yourself, update your reducers, etc.

It's a more of a manual process, but since your cases for not wanting to perform actions are pretty specific, it likely has to be done this way.

5
  • 1
    I like this solution. One question I have is if these actions could then be cancelled? Eg the user got bored waiting for the login to complete and navigated elsewhere, we may want to cancel the redirects which happen once the login call returns
    – dannym
    Commented Feb 21, 2017 at 18:45
  • Would you want to cancel the login though? The server would still be told that the user has logged in, but now the angular client has ignored the response and isn't in-sync with the server. Either way, I'm looking into this because I'm not sure of the answer
    – Adam
    Commented Feb 21, 2017 at 19:18
  • You may not want to cancel the login, but yo may want to cancel the redirect afterwards. Here is a situation - user goes to home page. On the home page there is a login form and an FAQ button. User puts in details and clicks login. While the request is processing they get bored and click on FAQ button and are taken to the FAQ page and start reading FAQs. Once your login request has returned you now do not want to redirect the user.
    – dannym
    Commented Feb 21, 2017 at 19:55
  • This is a contrived example, but there would be no issue if your redirect logic was in the HomePageComponent, and once the user moved to the FAQPageComponent the HomePageComponent had unsubscribed and would take no action
    – dannym
    Commented Feb 21, 2017 at 19:55
  • 1
    Sure, I can see that. I made an edit to my answer, basically you would just put a flag in your store to determine whether or not to cancel the actions or not.
    – Adam
    Commented Feb 21, 2017 at 20:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.