I can not figure out how to make a dynamic data update. Suppose there is an array of users objects, and I want to receive data about these users once a second using $http.get() . If it were not for the asynchrony, it would look like this:

 var users = []; setInterval(function () { for (var i = 0; i < users.length; i++) { $http.get('/user/'+i).then(function (res) { users[i] = res.data; }); } }, 1000); 

But when asynchrony comes into play, i naturally no longer equal to what is needed. To make the users[i].update(data) function that would also assign new data through the this object, the context of this is also lost (it becomes equal to the window )

UPDATE Found a solution, but it looks more like a crutch:

 var users = []; setInterval(function () { for (var i = 0; i < users.length; i++) { $http.get('/user/'+i).success((function (object) { return function (data) { for (var key in data) { object[key] = data[key]; } } })(users[i])); } }, 1000); 
  • if in your decision to capture only i - it will look better :) - Grundy
  • Never use setInterval! For periodic queries, otherwise overlap is provided to you at some point. Make the following query only after all the previous ones have been completed, for this you can use jquery.deferred. (besides, it is proxied by the $ q service) - Alexey Lemesh

1 answer 1

Use the query() method of the $resource service from the ngResource module to get all users.

In $http you can use headers and config to somehow mark a request to get users.

  • Tried to replace $http.get() with $resource('/user/:id') , and in the loop do users[i] = get({id: i}) every time working with one BUT: until the data arrived , nothing is displayed. Accordingly, the values ​​of the form disappear at the time of receiving data (until the promise is resolved) - Disminder
  • @Disminder, after the parameters in the $resource functions, you can specify handlers for success and error, in which you can assign - Grundy
  • @Grundy, again, the loss of context - this starts to point to the global object, the iterator variable is also lost. - Disminder
  • @Disminder, why do you need this ? you don't use it in any function - Grundy
  • @Grundy, here the code is just for example, the system is really more complicated. If in this case, how does the handler (success for example) find out in which object it needs to insert the incoming data? It would be possible for each object of the array to add an update method that would accept new data and add it just through this , and call this method as success but, as I said, this loses context. - Disminder