Search code examples
angularjsangular-servicesangular-controller

Problems using data from Service to Controller



I have a service and few controllers.
The service makes a post request and the controllers suppose to use the data sent back from the server.
Unfortunately, the RightsMainService.rightsArray returns an array with objects, and every object has only "undefined" fields.
Moreover, the RightsMainService.init is always false. Not sure where the problem is.

    app.service('RightsMainService', ['$http', '$rootScope', '$state',  function($http, $rootScope, $state) {

    var self = this;

    this.rightsArray = [];

    this.init = false;

    this.loadRights = function(rightsObject) {
        var config = {
            headers : {
                'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
            }
        };
        $http.post('./server/user.php', $.param(rightsObject), config)
            .success(function(data,status, headers, config) {
                self.rightsArray = data;
                self.init = true;
                $rootScope.$broadcast('finishLoadingEvent');
            })
            .error(function(data, status, header, config) {
                alert(status + " " + header);
                return;
            });
        $state.go('rights');
    }
}]);



    app.controller('RightsMainCtrl', ['$scope', '$rootScope', 'RightsMainService', function($scope, $rootScope, RightsMainService) {
    var rightsArrayInitialized = false;
    var rightsArray = [];
    (function Initialize(){
        if(RightsMainService.init == false) {
            alert("init");
            $rootScope.$on('finishLoadingEvent', function() {
                rightsArrayInitialized = true;
                rightsArray = RightsMainService.rightsArray;
                for(var key in rightsArray[0]) {
                    alert(rightsArray[key]);
                }
            })
        } else {
            rightsArrayInitialized = true;
            rightsArray = RightsMainService.rightsArray;
            for(var key in rightsArray[0]) {
                alert(rightsArray[key]);
            }
        }
    })();
}]);

Please ignore the alerts, they are there for testing purposes


Solution

  • You are calling $state.go('rights'); before the $http has completed. Whole flow process doesn't really make sense.