Thabo
Thabo

Reputation: 1465

Getting json file from local host using angularjs $http.get method

i am getting a JSON file from local host, i successfully get the data, i can see it when i console log, but when i inject the Factory in my controller it returns a null object, that means the variable erroMessages does not get the JSON object because the success function is not being executed before return in the Factory,please help.

    assetInModule.factory('helperFactory',function($http,$sce){
    'use strict';
    var title = "default";
    var errorMessages = {content:null};

    return {

        title : function(){ return title;},

        setTitle : function(newNitle){title = newNitle;},

        getErrorMessages : function(){

             $http.get('http://127.0.0.1/assetinspa/public/js/helpers/error_messages.json')
                  .success(function(data){

                    errorMessages = data;

                  });

                 return errorMessages; 
        }
    };
});

Upvotes: 0

Views: 574

Answers (2)

Ganesh Anil Kalumbe
Ganesh Anil Kalumbe

Reputation: 310

    "use strict";
assetInModule.factory("helperFactory", ["$http","$q",
    function ($http, $q) {


        var getErrorMessages = function() {
            var deferred = $q.defer();
            $http.get('http://127.0.0.1/assetinspa/public/js/helpers/error_messages.json')
                .success(function(data) {
                    deferred.resolve(data);
                });

            return deferred.promise;
        };

        return {

            title: function () { return title; },

            setTitle: function (newNitle) { title = newNitle; },
            GetErrorMessages: getErrorMessages
        }
    }
]);

At the time of use

helperFactory.GetErrorMessages().then(function(result){
//get the data
})

Upvotes: 1

TweetGeek
TweetGeek

Reputation: 21

try

assetInModule.factory('helperFactory',function($http,$sce){
'use strict';
var title = "default";
var errorMessages = {content:null};

return {

    title : function(){ return title;},

    setTitle : function(newNitle){title = newNitle;},

    getErrorMessages : function(){
         return $http.get('http://127.0.0.1/assetinspa/public/js/helpers/error_messages.json');
    }
};
});

angular.controller('YourCtrl', function ($scope, helperFactory) { 
  $scope.errorMessages = {};
  
  helperFactory
    .getErrorMessages()
    .success(function(data) {
      $scope.errorMessages = data;
    });
});

return is fired before $http.success end

Upvotes: 2

Related Questions