After calling the subscriber, I aim to fetch the events. This code successfully achieves this:
getCalendarData(){
var body = JSON.stringify({"cid": "etNG3V61LWS6Pzkeb_omuZGMVAOLd1_70tRQblVizWQ~",
"seldt":"2018-09-18"});
var headers = new HttpHeaders();
headers.append('Content-Type', 'application/json');
return this.httpClient.post(this.apiUrl, body, { headers: headers })
}
The above code runs perfectly and returns a JSON object.
However, when I try to call this method within getCalendarEvents(), I encounter a problem with returning the events due to the asynchronous nature of subscribe. How can I pass the events while requiring a return type?
getCalendarEvents(): Array<CalendarEvent> {
var listCal:any = []
this.getCalendarData().subscribe((data: any) => {
listCal = data;
console.log('listCal data: ', listCal);
let startDate: Date,
endDate: Date,
event: CalendarEvent;
let colors: Array<Color> = [new Color(200, 188, 26, 214), new Color(220, 255, 109, 130), new Color(255, 55, 45, 255), new Color(199, 17, 227, 10), new Color(255, 255, 54, 3)];
let events: Array<CalendarEvent> = new Array<CalendarEvent>();
for (let i = 1; i < listCal.length; i++) {
event = new CalendarEvent(listCal[i].title, new Date(listCal[i].date), new Date(listCal[i].date), false, colors[i * 10 % (listCal[i].colour.length - 1)]);
events.push(event);
}
//console.log(events);
return events;
}
);
//return events; HERE the events has no data because I am outside the .subscribe!
}