AngularJS 预先加载 json 文件

AngularJS eager loading json file

我是 angularJS 的新手。对不起,如果我对这个问题不清楚。

问题来了。

我有一个 JSON 大小为 20KB 的文件。当我尝试使用 'factory' 方法加载此文件时,我得到的是空值。

var app = angular.module('moonApp', []);

app.factory('MainSource', ['$http', function($http){
    var data={source:null};
    $http.get('/datafile.json',function(output){
      data.source=output;
      console.log(data.source); // it works
    });
    return data;
}]);

app.controller('appCtrl',['$scope','MainSource',function($scope,MainSource){
  console.log(MainSource.source); // Not works - getting Null value
}]);

对于上面的代码,我在控制台中得到了 NULL 值。但是如果我在 $http 成功方法中尝试它,它会呈现 json 文件内容。

请帮助我。提前致谢。

您可以在 MainSource 工厂上定义一个函数,并 return 一个您可以通过 then() 调用在您的控制器中解决的承诺。请试一试。

app.factory('MainSource', ['$http', function ($http) {

    function getSource() {
        return $http.get('/datafile.json', function () {
        });
    }

    return {
        'getSource': getSource
    }
}]);

app.controller('appCtrl', ['$scope', 'MainSource', function ($scope, MainSource) {

    MainSource.getSource().then(function (response) {
        console.log(response);
    });
}]);

这样试试:

console.log(MainSource.data.source);

我正在使用 $resource 读取 json 文件。下面的代码可以为你加载一个json文件。

var app = angular.module('moonApp', ['ngResource']);

app.module('moonApp')
.service('MainSource', function($resource) {
    return $resource('/datafile.json', {}, {
        query: {
            method: 'GET',
            isArray: true
        }
    });
})

现在,在控制器中注入并使用服务

app.controller('appCtrl',['$scope','MainSource',function($scope,MainSource){
   MainSource.query(function (data) {
    $scope.source = data;
    console.log($scope.source); // hopefully you'll see the JSON data here
   });       
}]);