-1

Through the following code, I'm loading JSON once:

$http.get('/data').success(function(mydata) {
    $scope.mydata = mydata;
});

I would like to watch for any changes coming from JSON and then reload the new data so I can update the $scope and consequently the view. I could use a JavaScript setInterval function to reload every 1 second but that seems a bit nasty. Any better solution? Perhaps something written in Angular itself?

trs
  • 863
  • 2
  • 16
  • 35

2 Answers2

2

I'm going to go ahead and make the assumption that what you're after is real time updates in your Angular application. There are quite a few different options these days that enable real time updates on the web but unfortunately $http is not one of them. Nor is any technology built on HTTP (the protocol) as it is inherently request/response based and doesn't support persistent connections.

Depending on your server side technology you could take a look at something like Socket.io (for Node) or SignalR (for .NET) as they offer nice abstractions over top of raw Websockets. There are also some great services out there that make real time web very easy to implement. One of the best ones right now is called Firebase. They were recently acquired by Google and have native angular bindings so that realtime push notifications are available directly in your controller scope.

If you don't own the server you're making requests from, unfortunately you're going to be stuck doing HTTP based polling on a timer. Be careful that you don't poll too often as you might create a performance hit for your clients or exceed API limits on the backend you're communicating with.

Jesse Carter
  • 20,062
  • 7
  • 64
  • 101
0

Long polling using $interval is one option

Another option is to notify clients of data updates using WebSockets

Kremlan
  • 310
  • 1
  • 7