我正在尝试以角度2连接几个http调用。我得到一个带有一个调用的环境数组。对于每个环境,我想返回另一个数组。并创建一个像
这样的对象firstObject [{名称: “姓名”,secondObject [东西,stuff2],名称: “NAME2”,secondObject [东西,stuff2]]
然而,当我尝试在数组中使用for循环时,具有readbe的惰性的东西使得很难遍历每个对象。我似乎在第二个订阅的每一个上都是一样的。我在代码下面有输出。任何帮助将不胜感激。
input2
低于
getEnvironments(app:string){
this.loading = true;
console.log("calling get Environments")
this._appModelService.getEnvironments(app).subscribe(val =>
{this.environments = val;
for(var i = 0; i < this.environments.length;++i){
console.log("Environment name = "+this.environments[i].EnvName);
this._appModelService.getAppTypes(app,this.environments[i].EnvName)
.subscribe(typeVal =>
{
console.log("Subscribing to i = "+i);
console.log(typeVal);
}
)
}
this.loading = false;
},
err => {
console.log("Something went wrong in get apps"); // Log errors if any
console.log(err);
this.loading = false;
});
}
修改 我的第一次通话的输出应该如下所示&lt;
calling get Environments
app-model.component.ts:93 Environment name = CRT
app-model.component.ts:93 Environment name = DRP
app-model.component.ts:93 Environment name = IFT
app-model.component.ts:93 Environment name = PRD
app-model.component.ts:93 Environment name = PRE
app-model.component.ts:93 Environment name = TRN
app-model.component.ts:97 Subscribing to i = 6
app-model.component.ts:98 [Object, Object, Object]
app-model.component.ts:97 Subscribing to i = 6
app-model.component.ts:98 [Object, Object, Object]
app-model.component.ts:97 Subscribing to i = 6
app-model.component.ts:98 [Object, Object, Object]
app-model.component.ts:97 Subscribing to i = 6
app-model.component.ts:98 [Object, Object, Object]
app-model.component.ts:97 Subscribing to i = 6
app-model.component.ts:98 [Object, Object, Object]
app-model.component.ts:97 Subscribing to i = 6
app-model.component.ts:98 [Object, Object]
第二个Call的输出将是
[ { EnvName: 'CRT ' },
{ EnvName: 'DRP ' },
{ EnvName: 'IFT ' },
{ EnvName: 'PRD ' },
{ EnvName: 'PRE ' },
{ EnvName: 'TRN ' },
我想将它们组合成一个嵌套对象。
答案 0 :(得分:2)
我们能看到服务的代码吗?
你应该像
一样链接 this._appModelService.getEnvironments(app).subscribe(
res => {
// data returned from response
// after data is returned/was a success
this._appModelService.someOtherCall().subscribe()
},
err {},
()
)
如果您需要使用相同的数据或混合数据,则需要使用flatMap链接不同的http请求。
答案 1 :(得分:0)
如果有人仍然需要解决上述问题。尝试使用forkJoin
。
getEnvironments(app:string): Observable<any> {
this._appModelService.getEnvironments(app)
.pipe(
//convert getEnvironments into...
mergeMap((environments:any[]) => {
//a join of multiple getAppTypes observables
return forkJoin(
environments.map(env => this._appModelService.getAppTypes(app, env.EnvName).pipe(
map(typeVal => {
return {/* an optional way to combine `env` and `typeVal` */}
})
))
).pipe(
map((typeVals:any[]) => { //post formatting to compile response object
return {/* a way to combine all the responses */}
})
)
})
)
}