Search code examples
javascriptangularrxjsngrx

Using map to map to property in rxjs


I was checking the ngrx docs, and I noticed the following code

  login$ = createEffect(() =>
    this.actions$.pipe(
      ofType(LoginPageActions.login),
      map(action => action.credentials),
      exhaustMap((auth: Credentials) =>
        this.authService.login(auth).pipe(
          // more code..
        )
      )
    )
  );

I am just wondering, what is the point of that map(action => action.credentials),? Cant we just use the payload directly in the exhaustMap without the extra map? like this:

  login$ = createEffect(() =>
    this.actions$.pipe(
      ofType(LoginPageActions.login),
      exhaustMap((login: LoginAction) =>
        this.authService.login(login.credentials).pipe(
          // more code..
        )
      )
    )
  );

Solution

  • yes, you can use it as you mentioned. also you could use destructuring

    login$ = createEffect(() =>
        this.actions$.pipe(
          ofType(LoginPageActions.login),
          exhaustMap(({credentials}) =>
            this.authService.login(credentials).pipe(
              // more code..
            )
          )
        )
      );
    

    or if you have more properties:

    login$ = createEffect(() =>
        this.actions$.pipe(
          ofType(LoginPageActions.login),
          exhaustMap(({credentials, flags}) =>
            this.authService.login(credentials, flags).pipe(
              // more code..
            )
          )
        )
      );