【问题标题】:Rxjs CombineLatest and Object.assign explanation for their usage at the @angular/material sourceRxjs CombineLatest 和 Object.assign 在@angular/material 源中的用法说明
【发布时间】:2020-06-24 08:36:17
【问题描述】:

我一直试图了解这段代码发生了什么。

我知道 combineLatest 发出一个值,从每个 observable 发出最后一个发出的值。 和 Object.assign 将所有可枚举的自身属性从一个或多个源对象复制到目标对象。

到目前为止,我了解这一点,但我不明白的是,它们是如何在这种情况下一起使用的(combineLatest 和 Object.assign)。

combineLatest(_route.pathFromRoot.map(route => route.params), Object.assign)

这是参考https://github.com/angular/material.angular.io/blob/master/src/app/pages/component-category-list/component-category-list.ts#L28

【问题讨论】:

    标签: javascript angular rxjs


    【解决方案1】:

    combineLatest 曾经有一个可选的resultSelector 参数,您可以在其中将结果映射到您想要的任何内容。所以他们使用Object.assign 作为resultSelector。此参数现已弃用,您应该改用map()https://github.com/ReactiveX/rxjs/blob/master/src/internal/observable/combineLatest.ts#L17

    所以他们使用这种语法将所有发射合并到一个对象中(顺便说一句,我认为这是使用Object.assign 的非常聪明的方式:))。

    我认为没有resultSelector参数的等效代码应该是这样的:

    combineLatest(_route.pathFromRoot.map(route => route.params))
      .pipe(
        map(Object.assign.apply),
      )
    

    resultSelector 函数接收结果作为单独的参数 (res1, res2, res3)combineLatest 在单个数组中进一步传播它们 ([res1, res2, res3]) 所以这就是为什么我不能只使用 map(Object.assign)

    【讨论】:

    【解决方案2】:

    Object.assign 用作投影函数参见this example

    _route.pathFromRoot.map(route => route.params) 将返回一个 Observable 数组。

    combineLatest 将获取 Array 的每个 Observable 的最新值,然后将它们传递给投影函数,从而生成一个具有所有参数作为属性的对象。

    【讨论】:

      猜你喜欢
      • 2017-06-25
      • 1970-01-01
      • 2021-04-28
      • 1970-01-01
      • 1970-01-01
      • 2021-10-08
      • 1970-01-01
      • 2022-01-24
      • 1970-01-01
      相关资源
      最近更新 更多