Within a component of my Angular application, I've subscribed to an Observable that returns a json array from a function in one of my services. That response is getting returned to the component correctly.
In .subscribe I am mapping fields from each JSON object into properties of a new class instance (object) using nested for loops and then adding/pushing each instance/object into an array of that class type.
When I view the results in the console in Chrome coming from console.log(this.contractsList), all fields are getting populated correctly with the exception of one which shows as:
listOffices: Array(0)
This string array should always have either 1 or 2 elements.
I realize I should probably be performing this deserialization/mapping within my service rather than the component however I dont think that is resulting in this issue. I plan on refactoring once I get it working. Rather, I think it relates to Closure which still confuses me quite a bit. I assume so because when I try console.log(officeval) anytime before I try to assign its value to the object, I see the correct values in the console.
Here is the method in my component that calls subscribe:
getContracts() {
this.contractService.getContracts().subscribe(
(res) => {
let officeval = new Array<string>();
for (var x = 0; x < res.length; x++) {
for (var z = 0; z < res[x].length; z++) {
if (res[x][z].resources.office !== undefined){
for (var a = 0; a < res[x][z].resources.office.values.length; a++) {
officeval.push(res[x][z].resources.office.values[a]);
}
}
else {
officeval.push("Not a Hive Policy");
}
this.createContract(res[x][z].id, res[x][z].name,"placeholder for type",res[x][z].isEnabled, res[x][z].service,
officeval, ["q", "w"], ["q", "w"],["q", "w"], ["q", "w"],["q","r"]);
} console.log(this.contractsList);
}
},
(err) => console.log(err))
console.log("logging contracts");
}
createContract(id:number, contractName:string, type:string, isEnabled:boolean,
service:string, listOffices:string[], listRooms:string[],
listSeats:string[], contractItemsEntries:string[], contractItemsOwners:string[], contractItemsSessions:string[]) {
this.contractsList.push (new Contract (id, contractName, type, isEnabled,
service, listOffices, listRooms,
listSeats, contractItemsEntries, contractItemsOwners, contractItemsSessions ));
}
}
Here is an example of the output in Chrome console:
[Contract, Contract, Contract...] x6
-opened Contract Array:
0:Contact
1:Contract
2:Contract
...
-opened Contract:
listOffices: Array(0) -- ???
listRooms: Array(2) --contain correct values
listSeats: Array(2) --contain correct values
id:1
isEnabled: true
service: contractService
type: "placeholder for type"