Home Angular JS batching many small requests
Reply: 2

Angular JS batching many small requests

NSPACE
1#
NSPACE Published in 2018-02-13 21:56:04Z

I am building a habit tracking application in AngularJS where users can input which habits they performed during the week. The interface is a table that looks like :

 
+--------+-------+-------+-------+-------+-------+
| Habit  | Date1 | Date2 | Date3 | Date4 | Date5 |
+--------+-------+-------+-------+-------+-------+
| Habit1 | Y/N   | Y/N   | Y/N   | Y/N   | Y/N   |
| Habit2 | Y/N   | Y/N   | Y/N   | Y/N   | Y/N   |
| Habit3 | Y/N   | Y/N   | Y/N   | Y/N   | Y/N   |
| Habit4 | Y/N   | Y/N   | Y/N   | Y/N   | Y/N   |
| Habit5 | Y/N   | Y/N   | Y/N   | Y/N   | Y/N   |
+--------+-------+-------+-------+-------+-------+

where each table cell (Y/N) can be toggled on or off. Each time one of these cells is clicked I am performing an API request to update the db. This results in many small requests being sent each session.

My question is - How would you batch all of these requests into a single request? What is the best approach for dealing with such a situation in AngularJs?

Bulkan
2#
Bulkan Reply to 2018-02-13 22:51:09Z

A simple solution would be to use an array to queue up requests.

Each time the user clicks a cell you can store the details in the queue.

Once the array reaches a certain size you can trigger a call to your API and reset your queue.

Slava Utesinov
3#
Slava Utesinov Reply to 2018-02-14 10:21:44Z

You can store requests, for example, at localStorage(to not lose them after page refresh) and Send them periodically via $timeout as one batch:

angular.module('app', []).controller('ctrl', function($scope, $timeout) {
  $scope.habbits = [];
  for (var i = 0; i < 5; i++) {
    var temp = { Name: 'Habbit' + (i + 1) };
    for (var j = 0; j < 5; j++)
      temp['Date' + (j + 1)] = undefined;
    $scope.habbits.push(temp);
  }

  //it is not needed at production code, just to overcome code snippet restrictions
  var localStorage = {
    data: {},
    getItem: function(key) {
      return this.data[key];
    },
    setItem: function(key, val) {
      this.data[key] = val;
    }
  }
  
  $scope.process = function(item, key) {
    item[key] = !item[key];    
    var old = JSON.parse(localStorage.getItem('requests'));
    old.push({
      Name: item.Name, Value: item[key], Key: key, id: (new Date()).valueOf()
    });
    localStorage.setItem('requests', JSON.stringify(old));
  }

  function Send(){
     $timeout(function() {
      var old = JSON.parse(localStorage.getItem('requests'));      
      var news = old.filter(function(x) { return !x.done; });
      if (news.length > 0)
        //http request mimic
        $timeout(function(){          
          console.log(JSON.stringify(news));                    
          old = JSON.parse(localStorage.getItem('requests'));
          for(var item of old)
            if(news.filter(function(x){ return x.id == item.id}).length == 1)
              item.done = true;
          localStorage.setItem('requests', JSON.stringify(old));          
          Send();
        }, 1000)
      else
        Send();
    }, 3000) 
  };  
  
  localStorage.setItem('requests', JSON.stringify([]));
  Send();
})
table,
th,
td {
  border: 1px solid black;
  border-collapse: collapse;  
}
.clickable{
  cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js">
</script>

<table ng-app='app' ng-controller='ctrl'>
  <thead>
    <tr>
      <td>Habit</td>
      <td ng-repeat='(key, value) in habbits[0]' ng-if='key!="Name" && key!="id"'>
        {{key}}
      </td>
    </tr>
  </thead>
  <tbody>
    <tr ng-repeat='item in habbits'>
      <td>{{item.Name}}</td>
      <td class='clickable' ng-repeat='(key, value) in item' ng-if='key!="Name" && key!="id"' ng-click='process(item, key)'>
        {{value == undefined ? 'Y/N' : (value ? 'Y' : 'N')}}
      </td>
    </tr>
  </tbody>
</table>

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.296043 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO