veliyat / angular-8-shopping-cart

This is the code which relates to the Angular 8 Shopping Cart Creation Tutorial on YouTube
https://youtu.be/k1kb-Aqy1t4
53 stars 51 forks source link

Why do we check the product exists? can't we get the quantity from the api as well? 🤔 #19

Open aminraeisi opened 3 years ago

aminraeisi commented 3 years ago

https://github.com/veliyat/angular-8-shopping-cart/blob/cf2bb543478d2e7d51029c9c465189aabc695acd/src/app/services/cart.service.ts#L24

veliyat commented 3 years ago

That is a good question. We are getting the quantity from the API already, but the idea is just to avoid more api calls per product in the cartItems array. Hence just ran the Product checking logic on the client side.

aminraeisi commented 3 years ago

@veliyat Thanks for the quick reply and great tutorial. I was thinking since we can always get the latest products from the api call (we are already getting all of them every time we add to cart), can we just don't check for quantity? I am expecting to get something like this in the response of the api:

{
    "id": "cartId",
    "products":[
        {
            "productID": 123,
            "quantity": 3,
            "price": 80
        },
        {
            "productID": 345,
            "quantity": 1,
            "price": 50
        }
    ]
}

If that is the case, then checking if the product exists will never run because we get every product from the api one time only. We will not get two products in the cart with the same id at all.

Thanks again for the great work! 👍🏻

veliyat commented 3 years ago

Thanks! Yes that is correct. However, product exists flag is just so that we don't overrun our loop. However, if you expect only one product and since it's client side, we can ignore that condition and safely loop through the entire product array as it would not consume much time doing so.