Using $resource.query on an array of objects

108 views Asked by At

Json

[ { "id":"0", "name" : "BCAA & GLUTAMINE", "brand" : "NRG FUEL", "price": "20", "description": "NRGFUEL 100% BCAA & Glutamine powder has been scientifically formulated to promote full muscle recovery, growth and repair whilst preventing muscle breakdown. Consisting of our instantized BCAA (2:1:1 RATIO) and absolute pure glutamine NRGFUEL’S BCAA and Glutamine powder will keep you in a positive state of growth and recovery. If you train hard, you need to recover hard.", "img" : "images/products/dietforcewhey.jpg" }, { "id":"1", "name" : "WHEY PLUS RIPPEDCORE", "brand" : "SCISMX NUTRITION", "price": "20", "description": "NRGFUEL 100% BCAA & Glutamine powder has been scientifically formulated to promote full muscle recovery, growth and repair whilst preventing muscle breakdown. Consisting of our instantized BCAA (2:1:1 RATIO) and absolute pure glutamine NRGFUEL’S BCAA and Glutamine powder will keep you in a positive state of growth and recovery. If you train hard, you need to recover hard.", "img" : "images/products/wheyplusrippedcore.jpg" } ]

controller

app.controller('productDetails', ['$scope', '$routeParams', 'productService', function ($scope, $routeParams, productService) {
$scope.products = productService.query();
$scope.product = $scope.products[$routeParams.id];


console.log($scope.product)

}]);

Service

app.factory('productService', ['$resource', function ($resource) {
return $resource('json/products.json'); 

}]);

when i console.log $scope.product i get 'undefined' but scope.products works fine.

could somebody explain what i am doing wrong please?.

1

There are 1 answers

1
Daniel Jamrozik On BEST ANSWER

Ah, this was always one of my biggest headaches when working with $resource!

The problem is that $scope.products = productService.query(); is asynchronous. What this means is that $scope.product will be set to something that does not exist yet. that is, the code skips over .query() straight to that line.

What you need to do instead is put that statement in the callback of asynchronous function, so that it runs when completed. Like so:

$scope.products = productService.query(function(result){
  $scope.product = result[$routeParams.id];
});

Hope that helps! :)