I am facing an issue where I need to update my property component with data received from the server.
In the Service, I have implemented something like this:
private events: Event[] = [];
eventChanged = new Subject<any>(); // Edit: added an observable
constructor(private http: HttpClient) {
this.http.get<Event[]>(this.baseUrl)
.subscribe(events => this.events = events);
this.eventChanged.next(this.events.slice()); //Edit: added an information to subscribers that events list changed
}
getEvents(): Observable<Event[]> {
return this.eventChanged.asObservable();
} // Edit: now I use this method to enables subscribers to observable
/* I don't use that method after Edit
showAllEvents(): Event[] {
return [...this.events];
}
*/
Next, I used the showAllEvents()
method in my component like so:
private events: Event[] = [];
private calendarEvents: CalendarEvent[] = [];
subscription: Subscription; // Edit: Added a Subscription
getInterestedEvents() {
// this.events = this.el.showAllEvents(); <-- I changed it into observable
this.subscription = this.el.getEvents()
.subscribe(
(events) => {
this.events = events;
});
this.events.forEach(eachEvent => {
let calendarEvent: CalendarEvent = {
start: subDays(startOfDay(new Date()), 1),
end: addDays(new Date(), 1),
title: eachEvent.name,
color: colors.red
}
this.calendarEvents.push(calendarEvent);
})
}
However, I am unsure how to make this.events
wait for the data from the service. Any suggestions? Each page presents a different challenge, and I am feeling quite puzzled.
Edit
Despite implementing subscribe and observable, this.el.getEvents().subscribe...
still does not return any data in my component.