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?
redirectRoute
, and then after login, theLoginSuccess
effect would navigate based on whereredirectRoute
specifies. You would only have oneloginSuccess
action, but it could redirect to anywhere.