0

我有ng2-charts正在使用我的Angular-cli構建的應用程序。我很新,所以任何幫助表示讚賞。我在Firebase上設置了數據。我在服務中創建一個訪問該數據的方法,當我使用此代碼時如何返回數組而不是FirebaseListObservable

getGraphData():Observable<any>{ 
     var graphData$ = this.af.database.list(`graphdata/${this.uid}`) 
      .map(tspa => tspa.map(tpa => tpa.$value)) 
      .do(console.log); 

     graphData$.subscribe(); 
     return Observable.of([]); 
} 

控制檯記錄正確的數據。

ex。 [1000, 5000, 2000]

的問題是,當我改變該方法返回的結果就像這樣:

getGraphData():Observable<any>{ 
     return this.af.database.list(`graphdata/${this.uid}`) 
      .map(tspa => tspa.map(tpa => tpa.$value)) 
} 

,並嘗試將其分配到一個組件中的變量。我總是得到的控制檯日誌:爲得到我想要的結果,如使用flatMapObservable.combineLatest()

>FirebaseListObservable 

我已經看到了不同的方法,但我不能讓任何其他結果。我有json數據,我想將其作爲數組分配給一個變量,以便將其顯示在我的條形圖中。

graph.ts

data$: any; 
    form$: any; 

    public barChartLabels:string[] = ['Account1', 'Account2', 'Account3', 'Account4', 'Account5', 'Account6', 'Account7']; 
    public barChartType:string = 'bar'; 
    public barChartLegend:boolean = true; 

    firstVar:any = [28, 48, 40, 19, 86, 27, 90]; 
    secondVar:any = [28, 48, 40, 19, 86, 27, 90]; 

    public barChartData:any[] = [ 
    {data: this.firstVar, label: 'Series A'}, 
    {data: this.secondVar, label: 'Series B'} 
    ]; 

我想分配firstVar新的火力地堡數據。有什麼建議麼?

我通常訪問的方法是這樣的:

ngOnInit() { 
    this.firstVar = this.transactionsS.getGraphData(); 
    console.log(this.firstVar) 

    } 

updateGraph(){ 
    this.firstVar = this.transactionsS.getGraphData() 
    console.log(this.firstVar) 

} 

回答

1

你沒有正確使用的觀測量,記住它的臺異步。

對觀測的簡要說明:
「RxJS是通過觀察序列構成異步和基於事件的程序庫。」
觀察點基於Observer/Subscriber pattern。基本上,在數據方面不認爲,根據事件來考慮。
當您使用此返回this.af.database.list('graphdata/${this.uid}')時,會創建一個observable,等待異步調用完成的事件(即收集的數據或錯誤)。 observers或rxjs - subscribers中使用的術語必須在觀察對象中註冊,告訴它我們對您的事件感興趣,如果有些數據出現,請將它傳遞給我們。可觀察者可以有多個用戶。
在你的情況下,不需要使用平面圖,只需傳遞數組,然後設置subscriber(val => this.firstVar=val)

getGraphData():Observable<any>{ 
    // create observable and add map operator for data to be sent to subscriber 
    return this.af.database.list(`graphdata/${this.uid}`) 
      .map(tspa => tspa.map(tpa => tpa.$value)); 
} 


firstVar:string[] = []; 
ngOnInit() { 
    // use subscribe to capture published data 
    this.transactionsS.getGraphData().subscribe((val)=> this.firstVar=val); 
    console.log(this.firstVar); // this will not work 

    } 

updateGraph(){ 
    this.transactionsS.getGraphData().subscribe((val) => this.firstVar=val); 

} 

rxjs有良好的文檔,檢查它here

+0

謝謝。我需要學習,我仍然會閱讀文檔。我注意到你的解決方案我沒有得到理想的結果,但至少我離得更近了。我必須在'getGraphData()'方法的末尾添加'.flatMap(list => list)'以獲得一個具有我所需數據的數組。一個可能無關的問題,'flatMap'通常會複製數據嗎? '[1000,1000,5000]'而不是'[1000,1000,5000,1000,1000,5000]'的數組。 ngOnit只會將val推到第一位對吧? – DauvO

+0

實際上我看到發生了什麼,但不知道如何解決它。當你訂閱一個observable時,我注意到一個控制檯日誌將以一個空數組開始,然後用一個新實例填充它,然後重複,直到完成。所以在3個項目中。它是[]然後[1000],然後[1000,5000],然後[1000,5000,1000],所以我的結尾數組將填充所有六個整數到一個數組中,因爲我相信導致的推送命令[1000,1000,5000, 1000,5000,1000]。 是否有另一個選擇使用比推?我想像集合會起作用。 – DauvO

相關問題