Angular $ http in the service, return

I have it 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 the controller. Guess this has something to do with returning from anonymous functions? Am I doing it wrong?

+4
source share
2 answers

Your function getOneProductdoes not return anything, which means that it implicitly returns undefined, therefore, an error.

$httpreturns a promise, and you must return this promise from your function. So change the 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){});
+2
source

You need to return Promisewhich 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);

factory :

 productsFactory.getOneProduct = function(){
      return $http.get('/api/products/' + $stateParams.productID);
    }
+2

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


All Articles