Getting json data with factory

I am trying to learn how to retrieve data inside a factory. I am currently using extraction data with a 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 fecting inside the 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; }); }]); 

this gives me an error that the data is not defined.

+5
source share
1 answer

You forgot to return singleItem from the promise of the find method. And then put .then for the promise to receive 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; }); 
+3
source

Source: https://habr.com/ru/post/1261593/


All Articles