【发布时间】:2017-06-02 06:38:40
【问题描述】:
我想在 Angular 2 中使用 ngFor 将 Firebase 查询的结果绑定到我的模板。这很容易在下面实现。
组件:
export class FeaturedThreadsComponent {
threads: FirebaseListObservable<any[]>;
qualitySubject: Subject<any>;
constructor(af: AngularFire) {
this.qualitySubject = new Subject();
this.threads = af.database.list('/threads', {
query: {
orderByChild: 'quality',
endAt: 5
}
});
}
}
模板:
<div *ngFor="let thread of threads | async">
{{thread.title}}
</div>
但是如果我想使用另一个嵌套在模板中的ngFor 指令来列出子对象的键...
<div *ngFor="let thread of threads | async">
{{thread.title}}
<div *ngFor="let participant of thread.participants">
{{participant.$key}}}
</div>
</div>
我收到控制台错误,Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.
在我的数据库结构中,participants 是 thread 的子代,threads 的子代thread 是动态键。所以我不能使用到participants 的直接路径。
这种嵌套ngFor 指令的模式在简单地迭代本地文件的服务中运行良好。为什么它在这里不起作用对我来说似乎有点模糊。
【问题讨论】:
-
我不这么认为。如果我使用实际密钥
{{participant.adam}}我会得到相同的控制台错误。我怀疑这与尝试迭代 Angular 2 无法识别为数组的对象participants有关。 -
thread.participants将是一个对象,并且不可与ngFor迭代。这是核心问题,所引用问题的公认答案应该可以帮助您解决这个问题。 -
threads: FirebaseListObservable<any[]>;将threads存储为可迭代的数组吗?这似乎是有道理的。这意味着这个问题更像是一个特定于 Firebase/Angularfire2 的使用问题。因为当participants是无法在直接路径中公开的动态键的子对象时,我需要一种方法将其放入可观察对象数组中。 -
是的,AngularFire2
listobservables 会发出数组值,所以它们可以与ngFor一起使用,但它们中的任何列表式属性都将表示为对象(即键和值)和@987654342 @ 不能直接与那些一起使用。引用的答案是您的解决方案。 (这就是为什么这是一个骗局。这不是罪过;这只是处理这些事情的方式。)
标签: angular firebase firebase-realtime-database angularfire2