本文介绍了将 FirebaseListObservable 结果转换为对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 angularfire-beta6.假设我有一个 myHeroes:FirebaseListObservable 并将它与我的模板中的 async 管道一起使用,我无法从 Hero 类访问函数.>

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>

这会导致错误:self.context.$implicit.someClassFunction() as hero 未转换为 Hero 类.我该怎么做?

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

推荐答案

您可以使用 AngularFireDatabase 上的列表或对象函数从数据库中获取对象或列表.您有 FirebaseListObserver 和一组预定义(不是您的自定义)类的对象.

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.

您必须手动将从 FirebaseListObservable 中的数据库获得的结果映射到自定义类的对象数组.

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

您可以将结果映射到名为 Heroes 的自定义类的数组中.您可以使用 lambda 表达式或将函数作为参数传递(本示例).

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

如果你得到 map 不是函数的错误,添加 import "rxjs/add/operator/map";

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

在 Hero 类中添加这两个静态函数:

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

这篇关于将 FirebaseListObservable 结果转换为对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-21 20:38