Search code examples
cachingangularangular2-httpangular2-observables

Angular2: Example with multiple http calls (typeahead) with observables


So I am working on couple of cases in my app where I need the following to happen

When event triggered, do the following

  • List item
  • check if the data with that context is already cached, serve cached
  • if no cache, debounce 500ms
  • check if other http calls are running (for the same context) and kill them
  • make http call
  • On success cache and update/replace model data

Pretty much standard when it comes to typeahead functionality

I would like to use observables with this... in the way, I can cancel them if previous calls are running

any good tutorials on that? I was looking around, couldn't find anything remotely up to date

OK, to give you some clue what I did now:

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

Missing debounce here

-- I ended up implementing lodash's debounce

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

onChartSelectionDebaunced: Function;

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

Solution

  • For debaunce you can use Underscore.js. The function will look this way:

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

    Regarding the cancelation of Observable, it is better to use Observable method share. In your case you should change the method getChartTable in your tableService by adding .share() to your Observable that you return.

    This way there will be only one call done to the server even if you subscribe to it multiple times (without this every new subscription will invoke new call).

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