As I retrieve data from an array of class People
, each person has an attendance list represented by Observable<any[]>
.
// Defining the Person class
class Person {
id: number;
name: string;
attendance: Observable<any[]>; // Represents an Observable array
}
// Creating an array of People (for simplicity)
people = Person[] = this.someService.getPeople();
My current task involves checking if any individuals in the group have an empty attendance list, assuming that
attendance: Observable<any[]>
will be an empty array []
when no data is found. The goal is to return true or false depending on the outcome of the validation within the validateAttendance()
method.
validateAttendance(): boolean {
// Loop through each person in the array to access their attendance list.
people.forEach(p => {
// Using a callback function to retrieve the list.
const func = (callback: (data) => void) => {
// Subscribing to get the attendance data
p.attendance.subscribe(list => {
callback(list);
});
}
// Attempting to retrieve and check the list using the callback function
// The issue arises as the 'result' variable turns out to be undefined.
const result = func(res => {
console.log(res); // Displays the attendance list for a given person
return res;
});
if (result.length <= 0) {
alert(`${p.name} has no attendance recorded - they might need a gentle nudge!`);
return false;
}
});
return true;
}
To resolve this, I experimented with incorporating a callback function inside the validateAttendance()
method to obtain the attendance list and return it. Unfortunately, the 'result' variable remained undefined!
Is there a way to successfully return a value from a callback function in this scenario?