问题描述
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)
})
);
}