Skip to content

Instantly share code, notes, and snippets.

@luizcieslak
Created August 8, 2017 01:34
Show Gist options
  • Save luizcieslak/dd9212b40db42e7a200fda20dbe00223 to your computer and use it in GitHub Desktop.
Save luizcieslak/dd9212b40db42e7a200fda20dbe00223 to your computer and use it in GitHub Desktop.
Retrieve many-to-many relationship data in Firebase
/*
* using:
* angular4.0.2
* angularfire2 4.0.0-rc0
* firebase 3.9.0
* rxjs 5.1.1
*/
export class HomePage {
user: FirebaseObjectObservable<any>;
groups: Observable<Array<{}>>;
events: Observable<Array<{}>>;
constructor(private _auth: AuthService, public afDB: AngularFireDatabase) {
this.user = this.afDB.object(`/users/${this._auth.uid}`);
this.user.subscribe(user =>{
if(user.groups){
this.groups = Observable.of(user.groups)
.map(obj => {
let arr = [];
Object.keys(obj).forEach((key) =>{
//get an Observable containing the info for each key in user.groups object.
arr.push(this.afDB.object(`groups/${key}`));
})
//zip() all Observables in the array
let zip = Observable.zip(...arr);
//return the emitted values (will return an Observable)
return zip;
})
//use switchMap() to flatten the Observables
.switchMap(val => val)
}
if(user.events){
this.events = Observable.of(user.events)
.map(obj => {
let arr = [];
Object.keys(obj).forEach((key) =>{
arr.push(this.afDB.object(`events/${key}`));
})
let zip = Observable.zip(...arr);
return zip;
})
.switchMap(val => val)
}
})
}
}
@luizcieslak
Copy link
Author

database 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
      }
    }
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment