Search code examples
javascriptangularjsjsonpromiseangularjs-factory

Fetching data json with factory


I am trying to learn how to fetch data inside factory. Currently I am using fetch data with the controller

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

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

product-detail.html

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

but when I change the code to move the fecthing inside factory like this 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];
                });
            }
        };

detail-product.js

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

it gives me an error that data is not defined.


Solution

  • You forgot to return singleItem from the find method promise. And then place .then over promise to get data from it.

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

    Controller

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