[AngularFire] Resolve snapshotChanges doesn't emit value when data is empty

Updated to AngularFire2 v5.0. 

One important change is that you need to call .snapshotChanges() or .valueChanges() to get data as Observable back.

    return this.db.list<Skill>(`skills/${this.uid}`)
      .snapshotChanges()

 

The problem is when there is no data, .snapshotChanges() never emit a value.

Luckly it is Observable, we can solve the problem by using .startWith():

  getSkills(): Observable<Skill[]> {
    return this.db.list<Skill>(`skills/${this.uid}`)
      .snapshotChanges()
      .startWith([])
      .map((actions) =>
        actions.map((action) => ({$key: action.key, ...action.payload.val()}))
      );
  }

If there is no data coming back from firebase, we still emit a empty array. This is much friendly if you work with Ngrx. Because if you depends on .snapshotChange() to emit a value back to switch map to next action, it might just block there, and your next action will never get dispatched.

posted @ 2017-10-18 22:53  Zhentiw  阅读(369)  评论(0编辑  收藏  举报