I am currently using the express-session
package to store product prices in my application. Everything seems to be functioning correctly, however I am encountering an issue when trying to display the session data in HTML. For example, if there are 2 products stored in the session and I add another one, the badge should display 3
. But when I refresh the page, the badge disappears and the next product added will show 4
. Additionally, attempting to display the session data like {{ session.cart.totalQty }}
is not working as expected. In this setup, main
serves as the controllerAs, cart
is a function responsible for adding products and calculating total price, while User.addToCart(...)
is a service function that returns $http
. My question is, how can I display the session totalQty
even after refreshing the page?
Here is the HTML code:
<sapn class="badge">{{totalQty}}</span>
<a data-target="#" ng-click="main.addCart(price)" class="btn btn-success btn-block">Add to cart</a>
This is the controller logic:
app.addCart = function(product){
User.addToCart($routeParams.id).then(function(data){
$scope.totalQty = data.data.cart.totalQty;
});
}
And finally, here is the API endpoint:
router.get('/add-to-cart/:id', function(req, res){
var cart = new Cart(req.session.cart ? req.session.cart : {});
Product.findById({ _id : req.params.id }, function(err, product){
if(err) throw err
if(!product){
res.json({success:false, message: 'err'});
} else {
cart.add(product, product.id);
req.session.cart = cart;
res.json({ success:true, product: product, cart:cart });
}
})
});