Casting FirebaseListObservable results to objects

纵饮孤独 提交于 2019-12-05 21:21:01

You can get an object or a list from the database using list or object function on AngularFireDatabase. You have FirebaseListObserver with an array of objects of predefined (not your custom) class.

Your will have to manually map the results obtained from the database in FirebaseListObservable to an array of objects of your custom class.


I suppose that your function to get your heroes from database looks like this:

myHeroes(): FirebaseListObservable<Hero[]> {
  return this.db.list('heroes');
}

You could map the result into the array of your custom class called Heroes. You could use lambda expression or pass the function as a parameter (this example).

myHeroes(): Observable<Hero[]> {
  return this.db.list('heroes').map(Hero.fromJsonList);
}

In case that you get an error that map is not a function, add import "rxjs/add/operator/map";


In Hero class add these two static functions:

static fromJsonList(array): Hero[] {
  return array.map(Hero.fromJson);
}

//add more parameters depending on your database entries and Hero constructor
static fromJson({id, name}): Hero {
  return new Hero(id, name);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!