Reputation: 81
I am working on a project with angular2/firebase and using angularfire2 module. I want some realtime data so I use angularfire2 list and on component side using subscribe over the list. In real-time scenario, if any new item added in firebase database it subscribe but without any query. How I can archive subscribe with query? I am using following code where the query is some selection on which basis I want data.
getRealtimeData(query: any){
if(query){
return this.af.database.list(databaseName+"/messages", {
query: {
orderByChild: 'is_broadcast',
equalTo: query.value
}
});
} else {
return this.af.database.list(databaseName+"/messages", {
query: {
orderByChild: 'timestamp'
}
});
}
}
I am calling this in my component creating a query
var query;
if (this.isBroadcastMessage && this.isGroupChatMessage || !this.isBroadcastMessage && !this.isGroupChatMessage) {
query = null;
} else if (this.isBroadcastMessage && !this.isGroupChatMessage) {
query = {
value: true
};
} else if (!this.isBroadcastMessage && this.isGroupChatMessage) {
query = {
value: false
};
}
this.firebaseService.getRealtimeData(query).subscribe((data: any) => {
console.log("data::", data);
}, (error: any) => {
console.log("error::", error);
})
Upvotes: 3
Views: 600
Reputation: 645
User ReplaySubject
query$: ReplaySubject<any> = new ReplaySubject(1);
First, create your getRealtimeData
function like this like this
// you no need to pass any argument here
getRealtimeData():FirebaseListObservable<any>{
return this.af.database.list(databaseName+"/messages", {
query: this.query$
});
then
public updateQuery(query: string): void {
this.query$.next(query);
}
Now
this.firebaseService.getRealtimeData().subscribe((data: any) => {
console.log("data::", data);
}, (error: any) => {
console.log("error::", error);
})
subscribe
function will be called when ever you call
this.firebaseService.updateQuery({
orderByChild: 'is_broadcast',
equalTo: true // false
});
// or
this.firebaseService.updateQuery({
orderByChild: 'timestamp'
});
Upvotes: 1