In my Angular 2 project, I am trying to chain multiple HTTP calls together. Initially, I retrieve an array of environments with one call. For each environment, I want to make another call and create objects like
firstObject[{name:"name",secondObject[stuff,stuff2],name:"name2",secondObject[stuff,stuff2]]
However, when I attempt to use a for loop in the array, the lazy nature of the subscribe function makes it difficult to iterate through each object. It seems that the same index is being used on each of the second subscribes. Below is the code output. Any assistance would be greatly appreciated.
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;
});
}
Output Below
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]
Edit The output of my first call should look like this<
[ { EnvName: 'CRT ' },
{ EnvName: 'DRP ' },
{ EnvName: 'IFT ' },
{ EnvName: 'PRD ' },
{ EnvName: 'PRE ' },
{ EnvName: 'TRN ' },
And the output of the second Call will be
[ { ServerTypeName: 'App ' },
{ ServerTypeName: 'Oracle ' },
{ ServerTypeName: 'Weblogic ' } ]
I aim to combine these into a nested object.