Reputation: 959
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
// functiion based on firebase DB
getWorkers():Observable<any> {
firebase.database().ref('/workers').on('child_added', (snapshot) => {
return snapshot.val();
});
}
subscriber function
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 .
Upvotes: 4
Views: 7897
Reputation: 954
firebase.database()
does not return an Observable so you cannot return it.
if you return Observable.of(val)
from within the callback function as suggested below, it will only return the callback function and not the outer getWorkers()
function.
You need to create an observable from the data returned from the callback.
I would use 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]...
})
here is some info from the docs
Upvotes: 3
Reputation: 929
your first method must return observable.
getWorkers():Observable<any> {
firebase.database().ref('/workers').on('child_added', (snapshot) => {
return Observable.of(snapshot.val());
});
}
Upvotes: 2