角度动态api调用



尝试调用从第一个api调用获得的api列表

loadData() {
this.http.get(this.firstApi).pipe(
.map(response => response.ip)
)
.subscribe(ip => {
console.log(ip);
Observable.forkJoin(
ip.map(
g =>
this.http.get('http://'+ip+':port/api/status')
.map(response => response.json())
)
).subscribe(res => {
//THIS WILL LOG GAME RESULTS SUCH AS HITS/PITCHES/STOLENBASES/RUNS...
let i;
res.forEach((item, index) => {
i = index;
console.log(res[i]);
})
})
});
}

问题是ip未定义。任何解决问题的方法。

一般来说,我需要的是

调用api->返回带有ip密钥和其他内容的对象列表(ip是相关的(。在获得的每个ip中调用状态api(返回一个json对象(,并将结果推送到一个数组。

我相信您已经混淆了rxjs映射和Array映射。pipe()内部的映射是由rxjs生成的,您可以利用它来修改返回的Observable。数组map返回一个新的数组。我看到你正在做两个订阅,而不是这样做,你可以使用mergeMap来伪造返回的Oberable。因此,为了提前为forkJoin制作Observables,这将使代码变得清晰。

loadData() {
this.http.get(this.firstApi).pipe(
mergeMap((firstResponse) => {
let obsevablesArray = firstResponse.map((eachOb) => this.http.get(`http://${eachOb.ip}:port/api/status`)); //  map from Array prototype
return forkJoin(...obsevablesArray)
})
).subscribe((dataFromAllIp) => {
console.log(dataFromAllIp);
// do the rest of your logic here.
})
}

我在这里给出了类似的答案。如果对您有帮助,请参阅。

下面提到的场景有什么可以获得的吗

调用api->返回带有ip密钥和其他内容的对象列表(ip是相关的(。在获得的每个ip中调用状态api(返回一个json对象(,并将结果推送到一个数组。

每当api返回将结果推送到数组时?

最新更新