我在Angular中使用Firebase实时数据库。我正在尝试实时从Firebase服务器获取一些数据:(服务代码(
getData(child){
return firebase.database().ref(child).on('value', (snapshot) => {
console.log(snapshot.val())
})
}
并在我的组件中订阅以上功能:
this.examinerService.getData('batches/names').subscribe(
(batches) => {
this.batches = batches.val();
}
)
这给我带来了错误:
Property 'subscribe' does not exist on type '(a: DataSnapshot, b?: string) => any'
我尝试使用 ref().once()
,但我想要实时行为。
更新:目前,我在组件中使用的database().ref().on('value', (snapshots) => { console.log(snapshots.val()); });
可以很好地工作,但我想在我的服务中进行操作并在组件中订阅它。有人告诉我,它不是一个可观察的,所以您无法订阅它。我是Angular的新手
函数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);
});
}
假设我们的数据结构看起来像这样
{
batches: {
names: [
{
first: 'FirstName',
last: 'LastName'
},
{
first: 'FirstName1',
last: 'LastName1'
}
]
}
}
对于名称,我们可能有一个看起来像这样的接口
export interface Name { first: string; last: string; }
然后我们有一项看起来像这样的服务
import { Injectable } from '@angular/core';
import { Name } from "./name";
import { AngularFireDatabase, AngularFireList } from "angularfire2";
@Injectable()
export class NameService {
constructor(private db:AngularFireDatabase) { }
getAllNames(): AngularFireList<Name> {
return this.db.list('batch/name');
}
}
最后我们的组件可以看起来像这样
import { Component, OnInit } from '@angular/core'
import { AngularFireList } from "angularfire2";
@Component({
selector: 'app-name-list',
template: `
<div *ngFor="let name of names$">
{{ name.last }}, {{ name.first }}
</div>
`
})
export class NameListComponent implements OnInit {
names$: AngularFireList<Name>;
constructor(private nameService: NameService) {}
ngOnInit() {
this.names$ = nameService.getAllNames();
}
}
Angular使用Websocket进行实时更新。我不确定,但我认为这可能是您要寻找的行为。
.subscribe()
无法工作,因为返回类型不是Observable
。您可以在回调函数中获得DataSnapshot
。尝试
getData(child){
return firebase.database().ref(child);
}
和您的组件
this.examinerService.getData('batches/names').on('value', (snapshot) => {
console.log(snapshot.val())
})