0

I have this code

PedidosService.getProductbyID($scope.listProductos.ProductID).then(function (d) {
            $scope.oneProduct = d.data.producto;                
        });

PedidosService is the name of my factory, getProductbyId is my http get request and $scope.oneProduct is the variable where i want store the result of this request.

factory.getProductbyID = function (id) {
    return $http.get('/Pedidos/GetProduct/' + id);
}

factory is my Factory and getProductbyID is my function to call http request

I call this code in a button. The first time that I click in the button, it returns a empty response '[]' but the next times that I click the button, it works fine!!!.

Thanks for you help

5
  • What is the code for your button? Commented Nov 1, 2016 at 18:12
  • 1
    have you checked the activity in network tab? Commented Nov 1, 2016 at 18:16
  • Could it be that id is not given for the first call, or different in the next calls? Commented Nov 1, 2016 at 20:06
  • The id value is always correct (the first time, too). The activity in network tab is OK except the first time Commented Nov 2, 2016 at 15:43
  • This is my code for my button PedidosService.getProductbyID($scope.listProductos.ProductID).then(function (d) { $scope.oneProduct = d.data.producto; }); $scope.pedido.Order_Details.push({ OrderID: OrderID = id, UnitPrice: $scope.UnitPrice, Quantity: $scope.Quantity, Discount: $scope.Discount, Products: $scope.oneProduct }); Commented Nov 2, 2016 at 15:47

1 Answer 1

0

As far as I know the $http.get returns a promise because that call is asynchronous. With that in mind a typical call to $http.get should be something like this:

$http.get('/someUrl', config).then(successCallback, errorCallback);

In your context I would have done it this way, so the factory returns a promise and in your controllers you will handle the success and error callback appropriately:

factory.getProductbyID = function (id) {
 var deffered = $q.defer();       
    $http.get('/Pedidos/GetProduct/'+ id)
        .then(function (result) {               
            deffered.resolve(result);
        }, function (data) {
            deffered.reject(data);
        });

    return deffered.promise;
 }
Sign up to request clarification or add additional context in comments.

3 Comments

He is already returning a promise (return $http.get(...)), no need for the $q wrapper.
Not working. This solution always returns an undefinied value (the first time and next times, too)
Can you post the result of the API call from the network tab in developer tools? Maybe the problem is elsewhere.

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.