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?

2 Answers 2

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){});
Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

Thx. But exaclty what do i type in my controller? Tried this but I get undefined. ProductsFactory.getOneProduct().then(function(d){ $scope.selectedProduct = d; });
What is it that is undefined? the $scope.selectedProduct? or the d?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.