1

I am new in ionic 4. I am doing shopping cart function. I want to delete the selected item. But it delete like pop function not delete the certain item. I have follow this tutorial : https://devdactic.com/dynamic-ionic-4-slides/

In service ts I am using this function then Cart.page.ts

onDeleteItem(i) {
const index = this.selectedItems.indexOf(i);
if (index > -1) {
this.cartServ.deleteFromCart(i);
this.selectedItems.splice(index, 1);
console.log(this.selectedItems);
}
this.total = this.selectedItems.reduce((a, b) => a + (b.count * b.price), 0);
}

Cart.service

    addToCart(product) {
        this.cartService.addProduct(product);
      }


    deleteFromCart(i) {
    const index = this.cart.indexOf(i);
    if (index > -1) {
      this.cart.splice(index, 1);
    }
}

Anyone can help me?

2
  • Is there is reason why you are using 2 duplicate lists. There should be a master list in the Cart service that the Cart.page.ts retrieves with a getter(). You shouldn't be maintaining 2 identical lists. Commented Jul 12, 2019 at 14:45
  • you should debug your code and watch variable's value Commented Jul 12, 2019 at 14:48

1 Answer 1

2

Don't pass the index to deleteFromCart function.

The reason is index of the deleting item in selectedItems array may not be the same index in cart items Array.

Pass the i which is the item, to deleteFromCart function and find the index and use splice.

onDeleteItem(i) {
    ...
    this.cartServ.deleteFromCart(i);
    ...
}

deleteFromCart(i) {
   const items = this.cart.filter(item => item.id === i.id);
   const index = this.cart.indexOf(items[0])
   if (index > -1) {
        this.cart.splice(index, 1);
   }
}
Sign up to request clarification or add additional context in comments.

5 Comments

Thank you for your reply, I already update my coding but after I change it did not change anything.
check whether value of index in deleteFromCart is not equal to -1
not length. I need to know value of index variable . deleteFromCart(i) { const index = this.cart.indexOf(i); console.log(index) if (index > -1) { this.cart.splice(index, 1); } }
ok that is the reason can you tell me what are attributes of the elements in selectedItems array
is item id, I totally follow this website devdactic.com/dynamic-ionic-4-slides

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.