2016-08-25 35 views
0

所以我工作的夫婦在我的應用程序,我需要的情況下例如,下面的情況發生Angular2:與多個HTTP調用(預輸入)與觀測

當事件觸發,請執行以下操作

  • 列表項
  • 檢查,如果有這方面的數據已經被緩存,緩存發球
  • 如果沒有緩存,反跳500ms的
  • 檢查是否有其他HTTP調用運行(同一康特XT)和殺死他們
  • 進行HTTP調用
  • 在成功緩存和更新/更換模型數據

當談到預輸入功能都是標準的

我想用觀測與此...順便說一句,如果以前的電話正在運行,我可以取消他們

有什麼好的教程呢?我環顧四周,找不到任何遠程保持最新

OK,給你一些線索,我現在做的事:這裏

onChartSelection(chart: any){ 

     let date1:any, date2:any; 

     try{ 
      date1 = Math.round(chart.xAxis[0].min); 
      date2 = Math.round(chart.xAxis[0].max); 

      let data = this.tableService.getCachedChartData(this.currentTable, date1, date2); 

      if(data){ 
       this.table.data = data; 
      }else{ 

       if(this.chartTableRes){ 
        this.chartTableRes.unsubscribe(); 
       } 

       this.chartTableRes = this.tableService.getChartTable(this.currentTable, date1, date2) 
       .subscribe(
        data => { 
         console.log(data); 
         this.table.data = data; 
         this.chartTableRes = null; 
        }, 
        error => { 
         console.log(error); 
        } 
       ); 
      } 

     }catch(e){ 
      throw e; 
     } 
    } 

缺少的防抖動

- 我最終實現lodash's debounce

import {debounce} from 'lodash'; 
... 

onChartSelectionDebaunced: Function; 

constructor(...){ 
    ... 
    this.onChartSelectionDebaunced = debounce(this.onChartSelection, 200); 
} 

回答

1

對於debaunce,您可以使用Underscore.js。該函數將這樣看:

onChartSelection: Function = _.debounce((chart: any) => { 
    ... 
}); 

關於可觀察的取消,最好是使用可觀測方法share。在你的情況下,你應該改變你的tableService中的方法getChartTable,將.share()添加到你返回的Observable中。

這樣,即使您多次訂閱(即使沒有這個每個新的訂閱都會調用新的調用),也只會有一個對服務器的調用完成。

看看:What is the correct way to share the result of an Angular 2 Http network call in RxJs 5?

+0

乾杯的建議...我想不下劃線添加到該項目的... JS資產已經大如爲:P ...會是不錯的有一個這個:)的角度版本將檢查共享方法;) –

+0

所以你應該嘗試使用你的項目中已經有的RxJS中的debounder:https://github.com/Reactive-Extensions/RxJS/blob/ master/doc/api/core/operators/debounce.md – Baumi

+0

查看代碼,但在http上下文中對我沒有意義...將解決它,謝謝 –