在 AngularFire2 中获取 FirebaseListObservable
Getting FirebaseListObservable in AngularFire2
我使用 AngularFire2 包将我的应用连接到 Firebase。我知道它已连接,因为当我在组件中执行以下操作时:
constructor(af: AngularFire) {
this.items = af.database.list('/items');
this.items.push({ attr: 'value' });
}
该项目被推送到 Firebase 中的正确列表。所以连接就在那里。但是,this.items 在尝试循环并在模板中显示它们时为空。还需要做什么才能显示这些项目?
<div *ngFor="let item of items | async">{{ item.attr }}</div>
编辑
这是一个 link 要点的实际代码,尽管它实际上几乎与这个问题中的内容完全一样。
https://gist.github.com/pjlamb12/0c3c680e3481c222f9b253224c7dd439
您需要订阅该列表,因此您需要执行以下操作:
因此,如果您的数据库中有如下项目列表:
-items
-item1
-name: 'mycoolitem'
-item2
-name: 'mycoolitem2'
然后在你的 TS 文件中:
//Items would have to be a list observable
items: FirebaseListObservable<any>;
//create an array for the returned items
itemsReturned: Array<any>;
constructor(af: AngularFire) {
this.items = af.database.list('/items');
this.items.subscribe((res) => {
this.itemsReturned = res;
});
}
然后在你的 HTML:
<div *ngFor="let item of itemsReturned | async">{{ item.name }}</div>
这会 return:
mycoolitem
mycoolitem2
希望对您有所帮助!
我使用 AngularFire2 包将我的应用连接到 Firebase。我知道它已连接,因为当我在组件中执行以下操作时:
constructor(af: AngularFire) {
this.items = af.database.list('/items');
this.items.push({ attr: 'value' });
}
该项目被推送到 Firebase 中的正确列表。所以连接就在那里。但是,this.items 在尝试循环并在模板中显示它们时为空。还需要做什么才能显示这些项目?
<div *ngFor="let item of items | async">{{ item.attr }}</div>
编辑
这是一个 link 要点的实际代码,尽管它实际上几乎与这个问题中的内容完全一样。
https://gist.github.com/pjlamb12/0c3c680e3481c222f9b253224c7dd439
您需要订阅该列表,因此您需要执行以下操作:
因此,如果您的数据库中有如下项目列表:
-items
-item1
-name: 'mycoolitem'
-item2
-name: 'mycoolitem2'
然后在你的 TS 文件中:
//Items would have to be a list observable
items: FirebaseListObservable<any>;
//create an array for the returned items
itemsReturned: Array<any>;
constructor(af: AngularFire) {
this.items = af.database.list('/items');
this.items.subscribe((res) => {
this.itemsReturned = res;
});
}
然后在你的 HTML:
<div *ngFor="let item of itemsReturned | async">{{ item.name }}</div>
这会 return:
mycoolitem
mycoolitem2
希望对您有所帮助!