ctrlz
ctrlz

Reputation: 1153

AngularJS Controller to update $scope automatically when backend data changes

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;

});

Upvotes: 0

Views: 1256

Answers (2)

cades kao
cades kao

Reputation: 118

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.

Upvotes: 3

Jonas
Jonas

Reputation: 1345

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

Upvotes: 0

Related Questions