Getting list of data with $key using angularfire2, firebase, async pipe and Angular 5+

Hi,

The angularfire2 is updated. It made some changes with compare to its previous version 4.X.
In new update of angularfire2, they replaced FirebaseListObservable with AngularFireList that we were using to get all data list from firebase.

There is also updates in .valueChanges(). Calling .valueChanges() returns an Observable without any metadata, so you cannot get $key from it. Now if you want to get $key then you need to use snapshotChanges();

Please check the changes here -
https://github.com/angular/angularfire2/blob/master/docs/version-5-upgrade.md

Now to get key with data, I am showing you example code here –
Let s assume I have a document named categories.

1- Create a new service named category
$ng g s category

2- Add category service in your provider in file “app.module.ts”
export class CategoryService {
//create a variable with type of Observable because snapshotChanges returns a observable type.
  observableCategories$: Observable<any>; 
// inject angular firedata base object  for communicating with firebase db “private db: AngularFireDatabase”
  constructor(private db: AngularFireDatabase) {
 // get all the list of data from 
    this.observableCategories$ = this.db.list('/categories', ref => ref.orderByChild('name'))
      .snapshotChanges();

  }
// now map your category key with data here
  getCategories() {
    return this.observableCategories$.map(changes => {
      return changes.map(c => ({ key: c.payload.key, ...c.payload.val() }));
    });
  }
}

Now category-component.ts code looks like that-



export class CategoryComponent {

categories$: Observable;
// inject category services in constructor “private catService: CategoryService”
constructor(private catService: CategoryService) {
// get and set categories$ with data.
this.categories$ = this.catService.getCategories();
}
}


Now category-component.html code looks like that-

<select ngModel name="category" id="category" class="form-control">
      <option value=""></option>
      <option *ngFor="let c of categories$ | async " [value]="c.key">
         {{c.name}} 
      </option>
 
    </select>




Comments

Popular Posts