我有一个简单的团队列表,首先我将每个团队都放在一个firebase文档中,并且在查询集合时可以很容易地用HTML显示它们*ngFor
。很简单的例子:
<ion-card *ngFor="let t of (team|async)" >
<ion-card-header>
<ion-card-title>name: {{t.name}} </ion-card-title>
{{t.pic}}
score = {{t.score}}
</ion-card-header>
</ion-card>
然后,我决定使用地图类型(json对象)测试将所有团队放在一个Firebase文档中。但是现在*ngFor
将无法正常工作。(我明白了为什么的本质,但无法解决):
这是数据库文档:
说这是新查询:
this.teams= this._db.collection('teams').doc("allteams").valueChanges();
然后,我尝试将响应设置为数组:(否则*ngFor
会显示错误)
this.team= this.teams.pipe(map((res: Response) => {return [res]}));
然后,在HTML中,我只能访问一个值,例如:
<ion-card *ngFor="let t of (team|async)" >
<ion-card-header>
<ion-card-title>name: {{t.team1.name}} </ion-card-title>
</ion-card-header>
</ion-card>
但我确实无法像以前那样展示:
<ion-card *ngFor="let t of (team|async)" >
<ion-card-header>
<ion-card-title>name: {{t.name}} </ion-card-title>
{{t.pic}}
score = {{t.score}}
</ion-card-header>
</ion-card>
我知道响应只是一个数组,但是无法将其转换为有效的数组。
我也尝试过类似的方法:
this.team= this.teams.pipe(map((res: Response)=> {for(let r in res){return r}}));
但这只会CONSOLE.LOG: team1, team2, team3
。其他所有数据都不存在。
衷心感谢您的帮助!:)
您的最后一次尝试非常接近,但是在这种情况下,您实际上仅返回了键(这是您观察到的行为)。
由于AngularFire在调用文档时仅返回原始文档值valueChanges
,因此您可以像直接处理对象一样对其进行操作。由于要返回给定键的值,因此只需要将其从对象中拉出即可。
尝试这个:
this.team = this.teams.pipe(map(res => {
return Object.keys(res).map(x => res[x]);
}));
此代码跨对象上的所有键进行映射,并返回这些键的所有值的数组。Angular / Ionic模板应该能够按照您期望的方式处理。
旁注:我已经切换到Object.keys
tslint喜欢为未过滤的抛出错误for x in obj
。
我也不太确定Response
这里是什么,因此为了清楚起见,我省略了类型-此代码实际上不是类型相关的。
当然,上面的代码并没有保留密钥。如果要这样做,可以:
this.team = this.teams.pipe(map(res => {
return Object.keys(res).map(x => {
const output = res[x];
output._key = x;
return output;
});
}));
只要确保您使用的属性(在本例中为_key
)就不会在对象上存在,否则它将被覆盖:)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句