Below is the Angular code block I have written:
demandCurveInfo = [];
ngOnInit() {
this.zone.runOutsideAngular(() => {
Promise.all([
import('@amcharts/amcharts4/core'),
import('@amcharts/amcharts4/charts'),
import('@amcharts/amcharts4/themes/animated'),
import('@amcharts/amcharts4/maps'),
import('@amcharts/amcharts4-geodata/worldLow'),
])
.then(modules => {
this.createDemandCurve(modules);
})
.catch(e => {
console.error('Error when creating chart', e);
});
});
}
This section is where API data retrieval is attempted.
async getDemandCurveInfo(statusType: string, valueType ) {
const params = [];
params.push({code: 'StreamCode', name: 'TG_PS'});
params.push({code: 'segmentCodes', name: ['US']});
params.push({code: 'checkinFrom', name: '2019-01-01'});
params.push({code: 'checkinTo', name: '2019-12-31'});
params.push({code: 'statusType', name: statusType});
params.push({code: 'valueType', name: valueType});
return await this.dashboardServiceHandler.getSegmentDemand([], params).toPromise();
}
The above method is called from within another function.
createDemandCurve(modules: any) {
const am4core = modules[0];
const am4charts = modules[1];
const am4themesAnimated = modules[2].default;
this.getDemandCurveInfo('REAL', 'TTV').then((data) => {
this.demandCurveInfo.push(data.valueOf().data);
console.log(this.demandCurveInfo[0]); <- first
});
console.log(this.demandCurveInfo[0]); <- second
}
In this scenario, attempting to access this.demandCurveInfo[0]
data outside of the function results in an output of undefined on the second console log. The first console log displays the expected output shown in this imagehttps://i.stack.imgur.com/fQ2xm.png. How can the console.log data be accessed outside of the function?