I am working with a basic database structure that includes information about groups, events, and users. Here is an example:
{
"groups": {
"123": {
"name": "developers",
"users": {
"1": true
},
"users_count": 1
}
},
"events": {
"456": {
"name": "Developers conference",
"users": {
"1": true
},
"users_count": 1
}
},
"users": {
"1": {
"name": "Jon",
"groups": {
"123": true
},
"events": {
"456": true
}
}
}
}
My goal is to display all the information about groups and events on the user's homepage. In the Homepage
class, I have written some code to achieve this:
After retrieving the user's data, I iterate through their groups and events, subscribe to each one, and add the retrieved data to respective arrays.
export class HomePage {
user: FirebaseObjectObservable<any>;
groupsKey: Array<any>;
groups: Array<any> = [];
eventsKey: Array<any>;
events: Array<any> = [];
constructor(private _auth: AuthService, public afDB: AngularFireDatabase) {
this.user = this.afDB.object(`/users/${this._auth.uid}`);
this.user.subscribe(user =>{
if(user.groups){
this.groupsKey = Object.keys(user.groups);
this.groupsKey.forEach(key => {
let groupObservable = this.afDB.object(`/groups/${key}`);
groupObservable.subscribe(group => {
this.groups.push(group);
})
})
}
if(user.events){
this.eventsKey = Object.keys(user.events);
this.eventsKey.forEach(key => {
let eventObservable = this.afDB.object(`/events/${key}`);
eventObservable.subscribe(event => {
this.events.push(event);
})
})
}
})
}
}
In the HTML section, I loop through the groups
array to display group names and user counts:
<div *ngFor="let item of groups">
{{item.name}}: {{item.users_count}} users
</div>
Although this method works initially, it results in duplicates being added to the arrays when updates are made to groups or events. Reloading the page solves this issue temporarily.
What would be a more efficient implementation for this scenario? I understand that using the async
pipe could help, but I am uncertain how to implement it.