使用angularjs $ http.get方法从本地主机获取json文件

时间:2016-05-17 12:09:27

标签: angularjs json

我从本地主机获取JSON文件,我成功获取数据,我可以在我控制台日志时看到它,但是当我在我的控制器中注入工厂时它返回一个空对象,这意味着变量erroMessages没有获取JSON对象,因为在工厂返回之前没有执行成功函数,请帮忙。

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

2 个答案:

答案 0 :(得分:2)

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

返回在$ http.success结束之前被触发

答案 1 :(得分:1)

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

使用时

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