I am working on an Angular project trying to push element into two arrays from an object. Returned undefined on the console (Edge browser). I did test the same code on the Visual Studio NodeJsConsole project, working fine.
Here is the code,
ngOnInit(): void {
this._salesDataService.getOrders()
.subscribe(res =>{
let data: any [] = [];
data.push(res);
let months: any [] = [];
let totals: any [] = [];
data.forEach(element => {
months.push(element.Month);
totals.push(element.totals);
});
console.log(data);
console.log(months);
console.log(totals);
});
}
Appreciate if someone can help me to figure this out - Thank You!
CodePudding user response:
So there is a key difference in your code here. The VS example that works uses stubbed data (on line 4 of your image). The Angular code is subscribed to getOrders(). Inspect the data that comes in (defined for you as res) and you'll likely see a difference.
The arrays are not undefined, they have 1 element, at index 0, named undefined. In other words your code pushed undefined into each array, which means your res data is not as you expect.
Also your VS code uses element.Month and element.Total but your Angular code uses element.Month and element.totals - inconsistent.
CodePudding user response:
From the first screenshot it looks like the result from the service, res, is an array. So you're pushing the res array into data array
Use res.forEach instead of data.forEach

