Angular2:带有observables的多个http调用(typeahead)的示例

时间:2016-08-25 11:08:02

标签: caching angular angular2-http angular2-observables

所以我正在我的应用程序中处理几个案例,我需要进行以下操作

触发事件时,请执行以下操作

  • 列表项
  • 检查具有该上下文的数据是否已缓存,提供缓存
  • 如果没有缓存,则去抖500ms
  • 检查其他http调用是否正在运行(对于相同的上下文)并将其终止
  • 进行http呼叫
  • 成功缓存和更新/替换模型数据

在预先输入功能方面非常标准

我想使用observables ...顺便说一下,如果先前的调用正在运行,我可以取消它们

有关这方面的任何好教程吗?我环顾四周,找不到任何最新的东西

好的,给你一些线索我现在做了什么:

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的去抖动

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

onChartSelectionDebaunced: Function;

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

1 个答案:

答案 0 :(得分:1)

对于豁免,您可以使用Underscore.js。该功能将以这种方式显示:

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

关于取消Observable,最好使用Observable方法share。在您的情况下,您应该通过将getChartTable添加到您返回的Observable中来更改tableService中的方法.share()

这样,即使你多次订阅它,也只会对服务器进行一次调用(没有这个,每个新的订阅都会调用新的调用)。

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

相关问题