【问题标题】:Angular 9 service nested http requestsAngular 9服务嵌套的http请求
【发布时间】:2021-10-03 10:52:11
【问题描述】:

我需要对 2 个单独的端点进行查询,以提供我的组件所需的对象。

No Endpoint Response
1 /registry/colors {"colors":["red","green","blue","orange"]}
2 /color/{colorName} {"name":"red", "details":["detail1","detail2", "detail3"]}

对于颜色数组中的每种颜色,我需要调用颜色细节端点并将所有这些颜色细节收集到一个颜色数组中。

getColors(): Observable<Color[]> {
  return this.http.get<ColorRegistry>(this.registryUrl).pipe(
    map((registry:ColorRegistry) => registry.colors.concatMap((colorName: string) => {
      return this.http.get<Color>(this.colorUrl+"/"+colorName);
    }))
  )
}

我希望上述方法返回以下内容:

[
 {"name":"red", "details":["detail1","detail2", "detail3"]},
 {"name":"green", "details":["detail1","detail2", "detail3"]},
 {"name":"blue", "details":["detail1","detail2", "detail3"]},
 {"name":"orange", "details":["detail1","detail2", "detail3"]}
]

显然我的做法是错误的,我正在寻找正确的方法来使用可观察对象执行嵌套请求。

【问题讨论】:

    标签: angular rxjs rxjs6


    【解决方案1】:

    你的方向是对的。

    尝试以下更改。

    1. map 运算符替换为更高阶的映射运算符,例如switchMap
    2. 使用 JS Array#map 并将 colors 数组属性中的每个条目替换为第二次调用的响应。
    3. 使用forkJoin并行触发请求,最后合并结果。
    getColors(): Observable<Color[]> {
      return this.http.get<ColorRegistry>(this.registryUrl).pipe(
        switchMap((registry: ColorRegistry) => {
          return forkJoin(
            registry.colors.map((colorName: string) => 
              this.http.get<Color>(`${this.colorUrl}/${colorName}`)
            )
          ) as Observable<Color[]>;    // <— assert type here
        })
      );
    }
    

    【讨论】:

    • 这告诉我Observable&lt;unknown[]&gt; is not assignable to type 'Observable&lt;Color[]&gt;'.
    • @Joel:我已经调整了帖子以添加类型断言。
    【解决方案2】:
    registryUrl = '/registry/colors';
    
    colorUrl(color) {
      return `/color/${color}`;
    }
    
    return this.http.get<ColorRegistry>(this.registryUrl).pipe(
      map(registry => from(registry.colors))
      forkJoin(color => this.http.get<Color>(this.colorUrl(color)))
    );
    

    【讨论】:

    • 这告诉我“Observable”类型的参数不可分配给“OperatorFunction”类型的参数。
    猜你喜欢
    • 2016-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-25
    • 2017-03-07
    • 1970-01-01
    相关资源
    最近更新 更多