Rob*_*ams 6 firebase firebase-realtime-database angular
我在角度使用firebase实时数据库.我试图从firebase服务器实时获取一些数据:(来自服务的代码)
getData(child){
return firebase.database().ref(child).on('value', (snapshot) => {
console.log(snapshot.val())
})
}
Run Code Online (Sandbox Code Playgroud)
并订阅我的组件中的上述功能:
this.examinerService.getData('batches/names').subscribe(
(batches) => {
this.batches = batches.val();
}
)
Run Code Online (Sandbox Code Playgroud)
这给了我错误:
Property 'subscribe' does not exist on type '(a: DataSnapshot, b?: string) => any'
Run Code Online (Sandbox Code Playgroud)
我尝试使用ref().once()哪个工作正常,但我想要实时行为.
更新:目前我database().ref().on('value', (snapshots) => { console.log(snapshots.val()); });在我的组件中使用它工作正常,但我想在我的服务中做它并在我的组件中订阅它.有人告诉我,它不是一个可观察的,所以你不能订阅它.我是角度新手,所以我不知道如何制作一个可观察的并用它绑定快照.
该函数getData返回传递的回调而不是Observable代码似乎期望的回调.您可以修改此功能,以便返回Observable您可以.subscribe()使用的功能.
import { Observable } from 'rxjs/Observable';
getData(child) {
return Observable.create(subscriber => {
const ref = firebase.database().ref(child);
const callbackFn = ref.on('value',
// emit a value from the Observable when firebase data changes
(snapshot) => subscriber.next(snapshot.val()),
// error out the Observable if there is an error
// such as permission denied
error => subscriber.error(error)
);
// The function passed to Observable.create can return a callback function
// which will be called when the observable we created is unsubscribed from.
// Just as we used `ref.on()` previously our callback function calls `ref.off`
// to tell firebase that we are no longer interested in the changes
return () => ref.off('value', callbackFn);
});
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
851 次 |
| 最近记录: |