Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I have a factory that looks like such:

app.factory('thingFactory', function($http) {

    var factory = {};   
    var things = [];

    factory.refreshThings = function() {
        return $http.post('/GetThings');
    }

    factory.initializeThings = factory.refreshThings()
        .then(function(response) {
            things = response.data;
        }, function(response){
            // some error handling code here...
        });

    factory.getThings = function() {
        return things;
    }

    return factory;
}

and a controller

app.controller('myController', function($scope, thingFactory) {
    $scope.things = thingFactory.getThings();
}

Because of the asynchronous nature of promises, and other collections being initialized (in addition to things), should I be concerned with getThings() returning an empty array, and thus, returning before the $http.post() call has resolved?

Is this a better alternative?

app.controller('myController', function($scope, thingFactory) {
    $scope.things = []

    thingFactory.initializeThings
        .then(function(response) {
            $scope.things = response.data;
        }, function (response) {
            // some error handling code here...
        });
}

Is there a safe alternative, where I can get the controller to not think about the promise and just safely get the collection from the factory?

share|improve this question

1 Answer 1

I would resolve things using router. Example using ui-router (https://github.com/angular-ui/ui-router) resolve feature (not tested):

app.service('thingService', function($http) {
    this.getThings = function() {
        return $http.post('/GetThings');
    }
}

app.controller('myController', function($scope, things) {
    $scope.things = things;
}

$stateProvider.state('myState', {
      resolve: {
         things: function(thingService){
            return thingService.getThings();
         }
      },
      controller: 'myController'
})

Promise returned by service will be automatically resolved before controller is instantiated. ngRoute has resolve functionality as well.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.