【问题标题】:Calling http.get multiple times in a RxJS pipeline在 RxJS 管道中多次调用 http.get
【发布时间】:2021-07-09 16:04:19
【问题描述】:

我需要在一个独特的 RxJS 管道中多次处理 http.get 响应。这是 JSON 响应的一部分:

[
  {
    "id": 1,
    "layerName": "Primary",
    "hierarchyCount": 2,
    "layerHierarchies": [
      {
        "hierarchyOrder": 1,
        "id": 3,
        "name": "Secant Piles"
      },
      {
        "hierarchyOrder": 2,
        "id": 6,
        "name": "As-Designed"
      }
    ],
    "gisViewTypeId": "M1",
    "coordinateSystemId": 5,
    "verticalCoordinateSystemId": 7,
    "measurementUnitSymbol": null,
    "color": "#fabed4",
    "stroke": true,
    "weight": 3,
    "opacity": 1,
    "fill": true,
    "fillColor": "#f032e6",
    "fillOpacity": 0.2,
    "active": false,
    "pointTypeId": 2,
    "shiftX": 0,
    "shiftY": 0
  },
...
]

通过以下管道,我得到hierarchyCount 的最大值,如下所示:

    this.layerHierarchi$ = this.http.get<LayerHierarchiesEntity[]>(baseURL + "Structure/StructureHierarchy", { params: layerParams, headers: headers })
    return this.layerHierarchi$.pipe(
      mergeMap((value) => from(value)),
      pluck("hierarchyCount"),
      max(),
      // mergeMap(maxHierarchyCount => this.layerHierarchi$),
    )

如您所见,在注释的管道的最后一行中,我尝试获取原始的http.get 响应以继续处理。 我不确定在 mergeMap 运算符中进行另一个调用是否正确,或者是否有另一种技术或 RxJS 运算符来处理这个问题?换句话说,我在整个管道中多次需要原始响应。

【问题讨论】:

    标签: angular rxjs http-get


    【解决方案1】:

    如果我理解正确的问题,我会考虑按照这些思路的解决方案。内嵌评论

    this.layerHierarchi$ = this.http.get<LayerHierarchiesEntity[]>(baseURL + "Structure/StructureHierarchy", { params: layerParams, headers: headers })
    return this.layerHierarchi$.pipe(
      // process the result of the http call and extract within the function passed to mergeMap
      // you should use the map operator
      map((value) => {
          // the following map is the array method, NOT the map rxjs operator
         hierCounts = value.map(v => v.hierarchyCount);
         hierMax = Math.max(...hierCounts)  // assume hierarchyCount is a number
         return [value, hierMax]
      }),
      mergeMap(([value, hierMax]) => // do what you need to do to continue processing),
    )
    

    一些额外的注意事项。

    您一直在使用mergeMap 运算符向它传递一个函数,该函数返回一个由您传递一个数组的from rxjs 函数创建的 Observable。

    除非您有充分的理由这样做,否则我更愿意像我的示例中那样使用 javascript 数组函数来处理数组。

    如果在进一步处理中需要执行其他级联 http 调用,请考虑使用 concatMap 而不是 mergeMap。您可以通过 http in this article 找到有关 rxjs 典型使用模式的一些灵感。

    【讨论】:

    • 我了解您的解决方案,但这不是解决问题的 Angular 方法。如您所见,原始 JSON 文件是一个对象数组。您必须使用 forof 运算符拆分数组才能使用 max 运算符。
    • 我建议使用Mathmax 函数而不是max rxjs 运算符
    猜你喜欢
    • 2020-02-01
    • 2017-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多