0

regarding the question Passing data between controllers in Angular JS? I ran into the situation that my ProductService is executing some $http(RestFUL Service) and returns NULL because the callback function isn't completed.

Because the p.getProducts() function is evaluted and the callback function which fetches the data from the RestFUL service, is'nt complete the function returns always null.

app.service('productService', function() {
    p = this
    p.productList = [];

    var addProduct = function(newObj) {
        productList.push(newObj);
    }

    p.getProducts = function(){
        return $http(RestFUL Service,function(data){p.productList.push(data)});
    }

    return {
        addProduct: addProduct,
        getProducts: return p.getProducts();
    };

});

How can I solve this problem?

Community
  • 1
  • 1
Briefkasten
  • 1,964
  • 2
  • 25
  • 53

2 Answers2

0

You must play with callback's. The http is an async operation, and for that reason you can´t return a valid result right away. How invoke getProducts must set as parameter a function (callback) that will be invoked when http is completed - when data is available.

app.service('productService', function() {
p = this
p.productList = [];

var addProduct = function(newObj) {
  productList.push(newObj);
}

p.getProducts = function(callback){
  $http(RestFUL Service,function(data){
    p.productList.push(data)
    callback(data);//do something with data
  });
}

return {
addProduct: addProduct,
getProducts: p.getProducts
};
}

//invoking
getProducts(function(products){
    //do something with products
});
Vítor Marques
  • 349
  • 4
  • 11
0

If you change your service to look more like this

return {
  addProduct: addProduct,
  getProducts: p.getProducts
}

then in controller you can make it work like that

app.controller('myCtrl', function ($scope, productService) {
  var products = null

  productService.getProducts().then(function(response){
    //do something with data returned
  })
})

your getProducts return $http which itself returns promise, that's why the I used then in controller

maurycy
  • 8,455
  • 1
  • 27
  • 44