在Firebase中的Angular中使用Observable和Subscribe [英] Using Observable and Subscribe in Angular with Firebase
问题描述
我正在尝试订阅一个函数,该函数返回angular 2中的可观察对象.因此,当添加任何新工作程序时,主调用函数应具有值
I am trying to subscribe to an function returning observable object in angular 2 . So when there is any new worker added the main calling function should have the value
//基于Firebase数据库的功能
// functiion based on firebase DB
getWorkers():Observable<any> {
firebase.database().ref('/workers').on('child_added', (snapshot) => {
return snapshot.val();
});
}
用户功能
workers: any[];
public ngOnInit() {
this.db.getWorkers().subscribe(workers => this.workers = workers);
}
这是说函数返回类型不可观察,因此会引发错误.
It is saying the function return type is not Observable and hence throwing error .
推荐答案
-
firebase.database()
不返回Observable,因此您无法返回它.firebase.database()
does not return an Observable so you cannot return it.如果您按照下面的建议从回调函数中返回
Observable.of(val)
,它将仅返回回调函数,而不返回外部的getWorkers()
函数.if you return
Observable.of(val)
from within the callback function as suggested below, it will only return the callback function and not the outergetWorkers()
function.您需要根据回调返回的数据创建一个可观察的对象.
You need to create an observable from the data returned from the callback.
我将使用 Observable.bindCallback :
getWorkers():Observable<any> { let fn = firebase.database().ref('/workers').on('child_added', (snapshot) => { return snapshot.val(); }); return Observable.bindCallback(fn) as Observable<any> }
然后您可以将其用作任何可观察到的内容:
then you can use it as any observable:
this.getWorkers().subscribe(data=>{ ...[code]... })
这是一些信息来自文档
这篇关于在Firebase中的Angular中使用Observable和Subscribe的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!