AngularJS:从文件中读取 JSON 数组到工厂中以用于 ng-repeat

AngularJS: read JSON array from file into a Factory for use in ng-repeat

我想从 JSON 文件中读取一个数组并将其放入工厂中,以便它可以用作服务,然后使用该服务来填充 ng-repeat。这一切都会在页面加载时发生。

HTML:

<div ng-app="pageApp" ng-controller="productStreamCtrl">
    <div ng-repeat="product in products">
        <div>
            {{product.title}}
        </div>
        <div>
            {{product.descr}}
        </div>
    </div>
</div>

JS(来自 this question):

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

pageApp.controller('productStreamCtrl', function($scope, ProductStreamService) {
    $scope.products = ProductStreamService.obj.products; //Not sure how to call my array?
});

pageApp.factory('ProductStreamService', function($http) { 

    var obj = {products:null};

    $http.get('products.json').then(function(data) {
        obj.products = data;
    });  

    return obj;
});

JSON:

[{
    "title" : "Title 1",
    "descr" : "Description for product 1"
},{
    "title" : "Title 2",
    "descr" : "Description for product 2"
},{
    "title" : "Title 3",
    "descr" : "Description for product 3"
},{
    "title" : "Title 4",
    "descr" : "Description for product 4"
}]

当我 运行 所有这些代码放在一起时,我只得到一个空白屏幕。我已经能够在控制器中直接通过 $http.get() 调用在 ng-repeat 中显示数组(来自 this question,请参见下面的代码)...

pageApp.controller('productStreamCtrl', function($scope, $http) {
    $http.get('products.json')
        .then(function(result){
            $scope.products = result.data;                
});

...但我希望这个数组可以在全球范围内访问。我似乎无法让工厂工作。

我认为问题可能出在我如何从服务或异步传输中调用我的数组。我确实遇到了 JSON 语法错误,但我在工作控制器示例中遇到了同样的错误。有什么想法吗?

您在设置变量时未完成您的承诺。将您的工厂更改为 return 一个函数,然后在您的控制器中调用该函数。

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

pageApp.controller('productStreamCtrl', function($scope, ProductStreamService) {
    ProductStreamService.getProducts().then(function(data){
        $scope.products = data;
    }); 
});

pageApp.factory('ProductStreamService', function($http) { 


    function getProducts(){
       return $http.get('products.json').then(function(data) {
            return data;
        }); 
    } 

    return {getProducts: getProducts};
});