2016-08-25 59 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上下文中对我没有意义...将解决它,谢谢 –