4

I have this in my factory

productsFactory.getOneProduct = function(){
  $http({
    method: 'GET',
    url: '/api/products/' + $stateParams.productID
  }).
    success(function(data, status, headers, config){

      console.log(data);
      return data;
    }).
    error(function(data, status, headers, config){

    });
}

This is my controller:

$scope.selectedProduct = ProductsFactory.getOneProduct();

console.log(data) outputs the data i want. But I get 'undefined' when I call it from controller. Guess it got something to do with returning from anonymous functions? Am I doing it wrong?

Joe
  • 4,274
  • 32
  • 95
  • 175

2 Answers2

2

Your getOneProduct function does not return anything which means it implicitly returns undefined, hence the error.

$http returns a promise and you must return that promise from your function. So change your code to this:

productsFactory.getOneProduct = function(){
  return $http({
    method: 'GET',
    url: '/api/products/' + $stateParams.productID
  }).
    success(function(data, status, headers, config){

      console.log(data);
      return data;
    }).
    error(function(data, status, headers, config){

    });
}

Then in your controller:

productsFactory
    .getOneProduct()
    .then(response){});
Christoph
  • 26,519
  • 28
  • 95
  • 133
2

You need to return the Promise that is returned from $http:

productsFactory.getOneProduct = function(){
  return $http({
    method: 'GET',
    url: '/api/products/' + $stateParams.productID
  });
}

And then in your controller:

productsFactory.getOneProduct().then(successFunction, errorFunction);

You could simplify your factory call further:

 productsFactory.getOneProduct = function(){
      return $http.get('/api/products/' + $stateParams.productID);
    }
Simon
  • 2,810
  • 2
  • 18
  • 23
  • Thx. But exaclty what do i type in my controller? Tried this but I get undefined. ProductsFactory.getOneProduct().then(function(d){ $scope.selectedProduct = d; }); – Joe Sep 17 '13 at 17:30
  • What is it that is undefined? the `$scope.selectedProduct`? or the `d`? – Simon Sep 18 '13 at 14:20