2017-06-06 57 views
3

我正在與angular2/firebase和使用angularfire2模塊的項目。我想要一些實時數據,所以我使用angularfire2列表和組件端使用訂閱列表。在實時情況下,如果在Firebase數據庫中添加了任何新項目,則它會訂閱,但沒有任何查詢。我如何可以用查詢存檔訂閱?我正在使用下面的代碼,其中查詢是根據我需要數據的某些選擇。Angularfire2/Firebase - 查詢與angularfire2列表訂閱運行時不工作

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' 
      } 
     }); 
    } 
} 

我在我的組件調用此創建一個查詢

 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); 
     }) 
+0

可以提供使用'getRealtimeData'方法的組件代碼調用?還有一些你收到的對象的日誌? – nisanarz

+0

在描述中添加,我希望我的訂閱被查詢調用。但它不會被調用查詢 –

+0

奇怪,我之前嘗試過,它爲我工作。唯一的區別是我在我的組件內部而不是在服務中進行了數據庫列表查詢。你試圖這樣做? – nisanarz

回答

1

用戶ReplaySubject

query$: ReplaySubject<any> = new ReplaySubject(1); 

首先,創建getRealtimeData功能像這樣類似這樣的

// you no need to pass any argument here 
getRealtimeData():FirebaseListObservable<any>{ 
    return this.af.database.list(databaseName+"/messages", { 
     query: this.query$ 
    }); 

然後

public updateQuery(query: string): void { 
    this.query$.next(query); 
} 

現在

this.firebaseService.getRealtimeData().subscribe((data: any) => { 
     console.log("data::", data); 
    }, (error: any) => { 
     console.log("error::", error); 
    }) 

subscribe功能將被當過您打電話

this.firebaseService.updateQuery({ 
      orderByChild: 'is_broadcast', 
      equalTo: true // false 
     }); 
// or 
this.firebaseService.updateQuery({ 
      orderByChild: 'timestamp' 
     });