【问题标题】:How to return result after switchMap operatorswitchMap运算符后如何返回结果
【发布时间】:2020-05-12 03:48:47
【问题描述】:

我有嵌套 http 调用的服务。在第一次请求之后,我想用以前的结果再做一个,并在完成后返回所有数据。我需要使用 result["Expert"] 传递数据,它是一个包含对象 {User_key: key1} 的数组。所以 switchMap 的第一步是使用 map 运算符并生成 JSON,然后将其传递给 http 请求。

service.ts

getAreaByKey(key: string): Observable<Area> {
  return this.http.get<any[]>(`${this.API_URL}/v0/areas/${key}`).pipe(
    map(result => {
      return {
        key: result["Key"],
        name: result["Description"],       
        experts: result["Experts"]
      };
  }),
  switchMap(res => {
    res.experts.map(el => {
      let json_data = JSON.stringify(el["User_Key"]);
      this.expertService.getExpertsByKeys(json_data);
    });
  })
}

问题是我试图在switchMap之后返回数据,但它显示错误。我在开发工具中也看不到第二个请求。

【问题讨论】:

  • 首先,你必须返回一个 Observable 给switchMap,所以投影函数必须有return。然后我不完全确定你想要做什么。看起来你根本不需要使用switchMap

标签: angular rxjs


【解决方案1】:

我猜你正在寻找类似combineLatest 的东西?您有多个输入 observables,但对所有输入的结果感兴趣(即您的案例中的一组专家)。

试试这样的:

switchMap(res => {
    return combineLatest(res.experts.map(el => {
      let json_data = JSON.stringify(el["User_Key"]);
      return this.expertService.getExpertsByKeys(json_data);
    }));
  })

【讨论】:

    【解决方案2】:

    SwithMap 需要得到一个 observable 作为回报。你可以使用 forkJoin 来组合 result 的所有元素并生成另一个可观察到的 switchMap 可以在内部订阅。

    getAreaByKey(key: string): Observable < Area > {
      return this.http.get < any[] > (`${this.API_URL}/v0/areas/${key}`)
        .pipe(
            map(result => {
                return {
                    key: result["Key"],
                    name: result["Description"],
                    experts: result["Experts"]
                };
            }),
             switchMap(res => forkJoin([
               ...res.experts.map(el => this.expertService.getExpertsByKeys(JSON.stringify(el["User_Key"])))])
         )
        );
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-12
      • 2014-07-01
      • 1970-01-01
      相关资源
      最近更新 更多