markstewie
markstewie

Reputation: 9587

rxjs with angular 2 - how to chain observable stream

I'm making an app with angular2 and @ngrx/store... I'm new to rxjs and thinking in a reactive way... really struggling with how observables are chained.

I have an auth effect... currently looks like

@Effect() authenticate$ = this.updates$
.whenAction(AuthActions.AUTHENTICATE_REQUEST)
.switchMap(update => this.api.post('/authenticate', update.action.payload)
  .map((res:any) => this.authActions.authenticateSuccess(res.json()))
  .catch((err:any) => Observable.of(this.authActions.authenticateError(err)))
);

What I want to do is chain two extra actions when the request is successful.

  1. Navigate to the "home" page after success with this.router.navigate(['/']).
  2. Store the credentials in a LocalStorage service this.authService.store(credentials)

What do I need to do to incorporate these actions in to the stream?

Upvotes: 1

Views: 565

Answers (2)

bertrandg
bertrandg

Reputation: 3207

Best solution is to keep your effect like this and add another one to react to success action like this:

@Effect({dispatch: false}) authenticateSuccess$ = this.updates$
.whenAction(AuthActions.AUTHENTICATE_SUCCESS)
.do(credentials => {
    this.router.navigate(['/']);
    this.authService.store(credentials);
});

Where {dispatch: false} means "reacts to this action but don't send another".

Upvotes: 0

hholtij
hholtij

Reputation: 2936

Assuming that the order of execution of the last 2 statements is irrelevant, all you need to do is at the end of your current statement append

.flatMap(() =>
{
   this.router.navigate(['/']);
   this.authService.store(credentials);
});

Upvotes: 1

Related Questions