0

First of all, yes i did look at other answers but they didn't do the trick for me.

I'm currently working on an angularJS based shopping application. After building the cart, creating the neccesary functions and building the view i would like to optimize the "cart" by creating an "no page refresh", add_to_cart function. So after some struggeling with functions like $scope.push and an init() load the cart function i got a bit stuck. The cart is build by the following code:

Get the cart:

$scope.getCartItems = function() {
    // Get the cart
    $http.get('config/cart/getCart.php', {cache: false}).then(function (response) {
        $scope.cartItems = [];
        $scope.cartItems = response.data.cartItems;
        $scope.totalCartItems = [];
        $scope.totalCartItems = response.data;
        $scope.selectedCustomer = [];
        $scope.selectedCustomer = response.data;
    });
};

Add a product:

$scope.addToCart = function(product, stock_available) {
    var product_id = product.id;
    var product_name = product.name.language;
    var product_price = $('span[name="combinationTotalPrice' + stock_available.id + '"]').text();
    var product_size = $('span[name="product_attributes' + stock_available.id + '"]').text();
    var product_quantity = product.quantity;
    var product_id_attribute = stock_available.id_product_attribute;

    console.log(product_id_attribute);

    var request = $http({
        method: "post",
        url: "config/cart/getCart.php?action=addToCart",
        data: {
            product_id: product_id,
            product_name: product_name,
            product_price: product_price,
            product_size: product_size,
            product_quantity: product_quantity,
            product_id_attribute: product_id_attribute
        },
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        }
    });
    $scope.cartItems.push(request);
};

By clicking on a button all the data is obtained from the view and passed to the addToCart() function. I've checked everything and the data gets inserted. After a hard page refresh the new product is added to the cart. But i would like to remove the "hard page refresh" and use something like i've tried above: $scope.cartItems.push(request);.

Update

So after some tips from the comments i've created a service for the cart. Take a look at the updated code:

cartService

myApp.service('cartService', ['$http',function ($http, $scope) {
    return {
        getCartItems: function() {
            return $http.get('config/cart/getCart.php', {cache: false})
        }
        // any other methods for http calls;
    }
}]);

cartController and function add

myApp.controller('CartController', function($http, $scope, cartService) {
    $scope.getTheCart = function() {
        cartService.getCartItems()
            .then(function(response) {
                $scope.cartItems = response.data.cartItems;
                $scope.totalCartItems = response.data;
                $scope.selectedCustomer = response.data;
            })
    };

$scope.addToCart = function(product, stock_available) {
        var product_id = product.id;
        var product_name = product.name.language;
        var product_price = $('span[name="combinationTotalPrice' + stock_available.id + '"]').text();
        var product_size = $('span[name="product_attributes' + stock_available.id + '"]').text();
        var product_quantity = product.quantity;
        var product_id_attribute = stock_available.id_product_attribute;

        console.log(product_id_attribute);

        var request = $http({
            method: "post",
            url: "config/cart/getCart.php?action=addToCart",
            data: {
                product_id: product_id,
                product_name: product_name,
                product_price: product_price,
                product_size: product_size,
                product_quantity: product_quantity,
                product_id_attribute: product_id_attribute
            },
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            }
        }).then(function() {
            $scope.getTheCart();
        });
    };
});

So everything works fine, i can even see in the network tab that the new getCart.php is obtained with the new data. Sadly still my $scope and view isn't updated.

Update 2

So i've taken a look at the example and i've tried some things for myself. After some tries i came to a very weird conclusion: Using an ng-click refreshData action refreshes the data through the following function:

$scope.refreshData = function() {
    cartService.refreshData()
        .then(function(response) {
            $scope.cartItems = response.data.cartItems;
            $scope.totalCartItems = response.data;
            $scope.selectedCustomer = response.data;
        })
};

but calling this function directly like the example in the first answer (jsFiddle) => fiddle won't refresh the view and $scope

$scope.addToCart = function(product, stock_available) {
    return cartService.addToCart(product, stock_available)
        .then(function(response) {
        console.log(response);
            $scope.cartItems = response.data.cartItems;
            $scope.totalCartItems = response.data;
            $scope.selectedCustomer = response.data;
        // call the get() function
        $scope.refreshData();
    })
};

If you have any questions please let me know in the comments

PS: creating a JSfiddle would put me back with a lot of time since all the data is obtained through the Prestashop webservice

As always, Thanks in advance!

4
  • 2
    $http returns a Promise. If you want data from it, you need to resolve it: $http(...).then((res)=>{$scope.cartItems.push(res.data);}); Commented Jan 23, 2018 at 10:12
  • @AlekseySolovey $http({...}).then(function(response){ $scope.cartItems.push(response.data.cartItems); }); returns: $scope.cartItems.push is not a function Commented Jan 23, 2018 at 10:19
  • 1
    was $scope.getCartItems() called before $scope.addToCart(...) ? Because it initialises the array $scope.cartItems = []; Commented Jan 23, 2018 at 10:23
  • @AlekseySolovey Yes it is called before the $scope.addToCart Commented Jan 23, 2018 at 10:29

1 Answer 1

1

Seems like you are using wrong approach. All http calls should be made from services, not from controllers/components. Try to create a service for this. Don't forget to inject the service in your controller. So after all there will be something like this

for example:

$scope.cartItems = [];
$scope.getCartItems = function() {
cartService.getCartItems()
  .then(response => {
    $scope.cartItems  = response.data; // or response
  })
}

register service according to the docs and add method

return {
  getCartItems: function() {
    return $http.get('config/cart/getCart.php', {cache: false})
  },
  // any other methods for http calls;
}
Sign up to request clarification or add additional context in comments.

8 Comments

Could you share a full example?
Thank you for the full example. So i've created the service and added it to my controller. Everything works out fine. It's a great technique. sadly the $scope still isn't updated. Would you please take a look at the "update" section of the question?
Update is added
@Deathstorm you should have something like that jsfiddle.net/ADukg/17515 All http calls should be made from service even a post one.
Well i've included the fiddle example with some name adjustments. The console returns the new cart with the ng-click added data. Still the view isn't updated untill i use a hard refresh
|

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.