0

I have a Service which uses $http to 'get' some JSON data from a REST API. The Controller uses the Service to get this data and initialise it in the $scope. How can I make it so that every time the JSON API changes that change is updated in the $scope, and thus the view?

Controller:

app.controller('MainController', function ($scope, BuildService) {
    init();
    function init() {
        BuildService.getBuilds().then(function() {
            $scope.builds = BuildService.data();
        });
    }
});

Service:

app.service('BuildService', function ($http, $q) {

    var BuildService = {}; 

    var deffered = $q.defer();
    var data = [];  

    BuildService.getBuilds = function () {
        //return builds;

        $http.get('/api').
          success(function(d, status, headers, config) {
            // this callback will be called asynchronously
            // when the response is available
            data = d;
            deffered.resolve();

          }).
          error(function(d, status, headers, config) {
            // called asynchronously if an error occurs
            // or server returns response with an error status.
            deffered.reject();
          });

          return deffered.promise;

    };

    BuildService.data = function() { return data; };

    return BuildService;

});

2 Answers 2

3

This question is not AngularJS-specific. What you want to achieve is a real-time app.

Method 1: polling

Use $interval to check JSON API every 30 seconds or so.

Method 2: WebSocket-based notification

If you have control over the JSON API, you can create another WebSocket-based notification API. Whenever JSON API changes, notify client to fetch JSON API again.

Sign up to request clarification or add additional context in comments.

Comments

0

I'd say you really have too much unneccessary logic. Keep it simple and just go like that. If you want to reuse the GET you can do it in a getBuilds controller method.

app.controller('MainController', function ($scope, $http, BuildService) {
    init();
    function init() {
        $http.get('/api').
            success(function(data) {
                $scope.builds = data;
            });
    }
});

2 Comments

Ok thanks, thats better. But if the data changes how can i make update it the $scope automatically?
Your data will only change if you do a request. If you want to check your builds you have two options. You can implement polling, that means, you do the same GET as in your init-function every x seconds. Or you take a look into WebSockets, which enable you to have a duplex-connection between your page and the server, which enables you to listen on update now messages from the server.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.