I hope to be clear in my first question here.
I was trying to perform a sort on the exhibitors array and while troubleshooting I got these confusing logs in the console.
When I am console logging an array it shows the list of objects but logging an element of any index of the same array shows undefined.
I am aware of the nested subscriptions, there is an API flaw that will be fixed.
I got half an answer from work, I am trying to sort that array before the subscription ends, asynchronous behaviour I presume. So if I move the sorting method into the subscription after the exhibitor list gets built, the problem is solved.
One question remains, why the confusing logs in the console. If the subscription didn't end, shouldn't we get undefined for all? This made it so hard to debug.
Bellow is the context, method in an Angular component.
listExhibitors() {
this.listEx$ = this.exhibitorService.list().subscribe((res) => {
this.allExhibitors = res;
this.exhibitors = [];
this.exhibitorsFiltered = []
this.userId = this.auth.getUserId();
for (let exhib of this.allExhibitors) {
this.exhibitorService.get(exhib.idx).subscribe((res2: any) => {
let members = res2.members
members.forEach(member => {
if (member.userIdx === this.userId) {
console.log('Pushin user..')
this.exhibitors.push(exhib)
}
})
});
}
console.log(this.exhibitors) // logs in the console an array of objects
console.log(typeof (this.exhibitors)) // Object
console.log(this.exhibitors[0]) // undefined
this.exhibitorsFiltered = this.exhibitors.sort(function (a, b) {
return ((a.name < b.name) ? -1 : ((a.name > b.name) ? 1 : 0));
})
console.log(this.exhibitorsFiltered) // logs in the console same array of objects
console.log(this.exhibitorsFiltered[0]) // undefined
})
}
this is the code that works:
listExhibitors() {
this.listEx$ = this.exhibitorService.list().subscribe((res) => {
this.allExhibitors = res;
console.log(res)
this.exhibitors = [];
this.exhibitorsFiltered = []
this.userId = this.auth.getUserId();
for (let exhib of this.allExhibitors) {
this.exhibitorService.get(exhib.idx).subscribe((res2: any) => {
let members = res2.members
members.forEach(member => {
if (member.userIdx === this.userId) {
this.exhibitors.push(exhib)
}
})
this.exhibitorsFiltered = this.exhibitors.sort((a, b) => {
//handle null cases
if (!a && !b) { return 0; }
if (!a) { return 1; }
if (!b) { return -1; }
//both not null do actual compare
return a.name.localeCompare(b.name, navigator.languages[0]
|| navigator.language, { numeric: true, ignorePunctuation: true });
});
});
}
});
}