用工厂获取数据json

时间:2016-12-20 20:09:18

标签: javascript angularjs json promise angularjs-factory

我正在尝试学习如何在工厂内获取数据。目前我正在使用控制器获取数据

factory.js

angular
    .module('app')
    .factory('Product', ['$http', function($http){
        return{
            get: function(){
                return $http.get('https://raw.githubusercontent.com/vicariosinaga/learn/master/products.json').then(function(response){
                    return response.data;
                });
            }
        };
    }])

细节poduct.js

    angular
        .module('app')
        .controller('productDetailsCtrl',['$scope','$stateParams', 'Product', function($scope,$stateParams,Product){
            $scope.id=$stateParams.id;
            Product.get().then(function(data) {
                $scope.singleItem = data.filter(function(entry){
                    return entry.id === $scope.id;
                })[0];
            });
}]);

产品detail.html

<a href="{{singleItem.url}}">
<p>{{singleItem.id}}</p>    
<p>{{singleItem.name}}</p>
<img src="{{singleItem.image}}" alt="{{singleItem.name}}">  
</a>    

但是当我更改代码以便像这样在工厂内移动fecthing时  factory.js

return{
            get: function(){
                return $http.get('https://raw.githubusercontent.com/vicariosinaga/learn/master/products.json').then(function(response){
                    return response.data;
                });
            },
            find: function(){
                return $http.get('https://raw.githubusercontent.com/vicariosinaga/learn/master/products.json').then(function(response){
                    var singleItem = data.filter(function(entry){
                        return entry.id === id;
                    })[0];
                });
            }
        };

细节product.js

angular
    .module('app')
    .controller('productDetailsCtrl',['$scope','$stateParams', 'Product', function($scope,$stateParams,Product){
        Product.find($stateParams.product,function(singleItem){
            $scope.singleItem = singleItem;
        });
}]);

它给我一个错误,即没有定义数据。

1 个答案:

答案 0 :(得分:3)

您忘记从singleItem方法承诺中返回find。然后将.then放在承诺上以从中获取数据。

find: function(id){
    return $http.get('https://raw.githubusercontent.com/vicariosinaga/learn/master/products.json').then(function(response){
        var singleItem = response.data.filter(function(entry){
            return entry.id === id;
        })[0];
        return singleItem;
    });
}

<强>控制器

Product.find($stateParams.id).then(function(singleItem){
    $scope.singleItem = singleItem;
});