用工厂获取数据json

Ger*_*via 5 javascript json promise angularjs 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;
                });
            }
        };
    }])
Run Code Online (Sandbox Code Playgroud)

细节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];
            });
}]);
Run Code Online (Sandbox Code Playgroud)

产品detail.html

<a href="{{singleItem.url}}">
<p>{{singleItem.id}}</p>    
<p>{{singleItem.name}}</p>
<img src="{{singleItem.image}}" alt="{{singleItem.name}}">  
</a>    
Run Code Online (Sandbox Code Playgroud)

但是当我更改代码以在工厂内移动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];
                });
            }
        };
Run Code Online (Sandbox Code Playgroud)

细节product.js

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

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

Pan*_*kar 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;
    });
}
Run Code Online (Sandbox Code Playgroud)

控制器

Product.find($stateParams.id).then(function(singleItem){
    $scope.singleItem = singleItem;
});
Run Code Online (Sandbox Code Playgroud)