【问题标题】:Using map to map to property in rxjs使用 map 映射到 rxjs 中的属性
【发布时间】:2020-04-07 14:22:51
【问题描述】:

我正在查看 ngrx 文档,我注意到以下代码

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

我只是想知道,map(action => action.credentials), 的意义何在?我们不能直接在exhaustMap 中使用有效负载,而不需要额外的map 吗?像这样:

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

【问题讨论】:

  • 你试过这段特殊的代码吗?即你的建议是否有效?如果是,那么这纯粹是业务最佳实践,如果不是,那么这是正确使用 NGRX createEffect 的基本要求。

标签: javascript angular rxjs ngrx


【解决方案1】:

是的,您可以按照您提到的那样使用它。 你也可以使用解构

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

或者如果您有更多属性:

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

【讨论】:

  • 感谢您的回复,但是那里使用map 运算符的文档到底有什么意义?它是否添加了任何功能/逻辑?
  • 没什么特别的。只是作者编写文档的一种方式。如果你觉得map 是多余的,你可以跳过它。
猜你喜欢
  • 1970-01-01
  • 2011-03-01
  • 2019-07-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-29
相关资源
最近更新 更多