Created
August 8, 2017 01:34
-
-
Save luizcieslak/dd9212b40db42e7a200fda20dbe00223 to your computer and use it in GitHub Desktop.
Retrieve many-to-many relationship data in Firebase
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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) | |
} | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
database example: