微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

角度合并地图一个又一个http调用

如何解决角度合并地图一个又一个http调用

getDetails()方法返回一个Details[]并带有该数组,并且有一个name属性,我将其传递给另一个http调用

Details {
    name: String;

详细信息

 getDetails()
     return this.https.get("/someValue") //this return Details[] from here I have to take  name property

返回

{name : hello}

信息

 getinformations(name:string) {
    return this.https.get("/anotherValue"+"?"+ name)
 }

我正在尝试先致电getDetails()并将name属性传递给

information{
  Hieght:string
  age:string
}

getinformations()
this.getDetails().pipe(mergeMap(x => 
 this.getinformations(x.name)).subscribe((inforamtionResults:information[])=>{
  console.log("Checking informations"+inforamtionResults.length) 

返回

 {height:160,age: 23
   }

这不起作用,因为x值是一个数组。如何迭代数组并将数组属性作为参数传递?

解决方法

正如您所说,您需要迭代每个 this.getInformations(x.id) Details。您只需使用Array.map()即可完成此操作。但是,mergeMap想要一个可观察的对象,但是我们拥有的是一系列可观察的对象。幸运的是,我们可以使用rxjs'forkJoin将这些可观察数组与一个可观察数组组合。

this.getDetails()
  .pipe(
    mergeMap((details) =>
      forkJoin(details.map((x) => this.getInformations(x.id)))
    )
  )
  .subscribe((x) => console.log(x));

这里是sample demo。我使用了不同的API,但实现方式相似。

,

您需要尝试这样。

 getDetails() {
    return this.http.get("/someValue")
      .pipe(
        mergeMap((x) => {
          return this.getInformations(x.id)
        })
      );
  }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。