While working on my Angular application, I encountered an issue with deserializing data from an Observable into a custom object array. Despite successfully mapping most fields, one particular field named "listOffices" always appears as an empty array ([]). This is unexpected since it should contain either one or two elements.
The code snippet within the component that handles this mapping involves nested for loops to iterate through the JSON objects and map their values to properties of a new class instance. It seems like the problem lies in Closure, as I can see the correct values for "officeval" when logged before assigning them to the object.
Although I am aware that performing this deserialization logic within the service might be cleaner, I don't believe it's the cause of the issue. Once I resolve this bug, I plan to refactor the code accordingly.
Below is the method in my component responsible for the subscription:
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 ));
}
}
In the Chrome console, the output sometimes looks like this:
[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"