Joining 2 nodes with angularfire2

157 Views Asked by At

Image of my firebase

Im trying to map the categories that the user have favourited to the category node to retrieve its details.

Code for my typescript :

ionViewDidLoad(categorykey:string){
console.log('Hello Manage Favourite Page');
let userid = this.authData.getID();

this.favouritecategories = this.af.database.list(`/users/${userid}/favourites`)
  .map(favourites => {
    favourites.map(category => {
      let categorykey = category.$key
      console.log(categorykey);
      category.favname = this.af.database.object(`/test/${categorykey}`)
    });
      return favourites;
  });

Code for my Html:

<div *ngFor="let region of favouritecategories | async; let i = index;">

    <ion-item (click)=" category.hidden = !category.hidden; category.visible = !category.visible" detail-none><b>{{i+1}}.{{ (category.favname| async)?.name }}</b>
      <ion-icon name="arrow-down" [hidden]="category.visible" item-right></ion-icon>
      <ion-icon name="arrow-up" [hidden]="!category.visible" item-right></ion-icon></ion-item>

</div>

With the above code , i only managed to retrieve the category's name but not the regions name. Anyone have any idea on how to do?

1

There are 1 best solutions below

0
On

You haven't actually returned the modified map. You want to do something like the following (modified for latest AngularFire versions):

let listObservable = this.af.database.list(`/users/${userid}/favourites`);
// use snapshotChanges() as this contains the keys
this.favouritecategories = listObservable.snapshotChanges()
  .map(snapshots => {
    // note that we return the inner .map()!
    return snapshots.map(snap => {
      let data = snap.val();
      data.favname = this.af.database.object(`/test/${snap.key}`).valueChanges();
      // note also that we return the transformed data
      return data;
    });
  });

Differences from the original poster's question:

  • Should use .valueChanges() to get a useful observable for ngFor ops
  • $key is no longer included in data by default
  • But can be obtained using .snapshotChanges()

Some other useful tips:

  • Avoid sequential numeric ids (i.e. arrays) in distributed data
  • Write the data how you'll read it later
  • Avoid trying to make NoSQL look like SQL with lots of fkey references and artificial normalizing. Just store the names where you'll read them as a general rule.
  • It's okay to denormalize data.