将FirebaseListObservable结果投射到对象 [英] Casting FirebaseListObservable results to objects
问题描述
myHeroes:FirebaseListObservable< Hero []>
,并在模板中使用它与异步 Hero class。 < ul>
< li * ngFor =let heroHeroes>
{{hero.someClassFunction()}}
< / li>
< / ul>
这会导致一个错误: self.context。$ implicit.someClassFunction )
因为英雄不会被转换成英雄类。我怎样才能做到这一点?
您可以使用列表或对象函数获取数据库中的对象或列表 AngularFireDatabase
。你有 FirebaseListObserver
与预定义(不是你的自定义)类的对象数组。
您将不得不手动将从FirebaseListObservable中的数据库获得的结果映射到自定义类的对象数组。从数据库中得到你的英雄看起来像这样:
$ $ p $ myHeroes():FirebaseListObservable< Hero []> {
return this.db.list('heroes');
$ b您可以将结果映射到自定义类的名为Heroes的数组中。您可以使用lambda表达式或传递函数作为参数(本例)。
myHeroes():Observable< Hero [] > {
return this.db.list('heroes')。map(Hero.fromJsonList);
$ b $ p
$ b如果你得到一个map不是函数的错误, code> importrxjs / add / operator / map;
Hero类添加了这两个静态函数:
$ p $static fromJsonList(array):Hero [] {
return array.map (Hero.fromJson);
//根据数据库条目和Hero构造函数添加更多参数
static fromJson({id,name}):Hero {
return new Hero id,name);
}
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?
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);
}
这篇关于将FirebaseListObservable结果投射到对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!