Search code examples
angularauthenticationrxjsngrxeffect

Effect just call one time with two Observables in Rxjs 6


I have 2 functions in login features: get salt then login But when I dispatch the action Login, it just call 1 time (get salt one time) getSalt and logIn are Observable here.

Is my effect written correctly? Need some helps, I'm newbie with rxjs, thanks!

My effect

  @Effect()
  logIn$: Observable<any> = this.action$
  .pipe(
    ofType<LogIn>(AuthActionTypes.LOGIN),
    map((action: LogIn) => action.payload),
    switchMap(payload => {
      return this.authService.getSalt(payload.username)
      .pipe(
        map(data => {
          return this.authService.logIn(payload, data);
        })
      );
    })
  );

My get Salt

  public getSalt(username: string): Observable<string> {
    const url = `${host}/customers/${username}/salt`;
    console.log('url salt', url);
    return this._http.get<{ salt: string }>(url)
      .pipe(
        map(res => res.salt)
      );
  }

My login

  public logIn({username, password}: { username: string, password: string }, salt: string) {
    /../
    return this._http.get(url, {params, headers});
  }

Solution

  • You're mapping to a login Observable so you should use switchMap instead of map:

    switchMap(payload => this.authService.getSalt(payload.username).pipe(
      switchMap(data => this.authService.logIn(payload, data))
    ))