Osko
Osko

Reputation: 56

Casting FirebaseListObservable results to objects

I'm using angularfire-beta6. Let's say I have a myHeroes:FirebaseListObservable<Hero[]> and use it with an async-pipe in my template I cannot access functions from the Hero class.

<ul>
  <li *ngFor="let hero of myHeroes">
    {{hero.someClassFunction()}}
  </li>
</ul>

This results in an error: self.context.$implicit.someClassFunction() as hero is not cast to the Hero class. How would I do that?

Upvotes: 3

Views: 1271

Answers (1)

MiroO
MiroO

Reputation: 156

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);
}

Upvotes: 4

Related Questions