Angular Delete Item From Cart Without reload

I have a dilemma, I’m able to delete item from database collection carts, I figured out the reason I have to reload the cart to get update on cart, this is because item is being removed from database but not from the array. I tried a number of ways to delete from array but its not working for me. I tried using splice as well as indexOf. Can someone please point me in the right direction I would greatly appreciate it. I have included a snippet of necessary code.

CartItemComponent:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code> cartitems$: Cartitems[] = []
cartItems: CartItem [] = []
handleRemoveFromCart(){
alert("hit remove from cartitem");
/* this.cartService.RemoveProductFromCart(this.cartItem._id).subscribe(() =>
console.log("Product with Id deleted", this.cartItem._id
//this.cartitems$ = this.cartitems$.splice(this.cartItem._id) does not work
);*/ //didn't work
this.cartService.RemoveProductFromCart(this.cartItem._id).subscribe((index =>{
console.log("Product with Id deleted", this.cartItem._id),
this.result = this.cartitems$.findIndex(p => p._id === this.cartItem._id);
if(this.result > -1){
this.cartitems$.splice(this.result, 1);
alert("Remove from array")
}
}
}
</code>
<code> cartitems$: Cartitems[] = [] cartItems: CartItem [] = [] handleRemoveFromCart(){ alert("hit remove from cartitem"); /* this.cartService.RemoveProductFromCart(this.cartItem._id).subscribe(() => console.log("Product with Id deleted", this.cartItem._id //this.cartitems$ = this.cartitems$.splice(this.cartItem._id) does not work );*/ //didn't work this.cartService.RemoveProductFromCart(this.cartItem._id).subscribe((index =>{ console.log("Product with Id deleted", this.cartItem._id), this.result = this.cartitems$.findIndex(p => p._id === this.cartItem._id); if(this.result > -1){ this.cartitems$.splice(this.result, 1); alert("Remove from array") } } } </code>
 cartitems$: Cartitems[] = []

 cartItems: CartItem [] = []


  handleRemoveFromCart(){
    alert("hit remove from cartitem");
   /* this.cartService.RemoveProductFromCart(this.cartItem._id).subscribe(() =>
   

     console.log("Product with Id deleted", this.cartItem._id  

   //this.cartitems$ = this.cartitems$.splice(this.cartItem._id) does not work

  
   );*/ //didn't work

  this.cartService.RemoveProductFromCart(this.cartItem._id).subscribe((index =>{



console.log("Product with Id deleted", this.cartItem._id),

  this.result =  this.cartitems$.findIndex(p => p._id === this.cartItem._id);

   if(this.result > -1){
    this.cartitems$.splice(this.result, 1);
    alert("Remove from array")
     }

   }


 }
  

cartService:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code> RemoveProductFromCart(_id:string){
alert("show deleted item" + _id);
return this.http.delete<Cartitems[]>(this.rootUrl + '/getProducts/removecartitems/' + _id);
/* This goes back to calling function so I can try to delete from collection*/
}
</code>
<code> RemoveProductFromCart(_id:string){ alert("show deleted item" + _id); return this.http.delete<Cartitems[]>(this.rootUrl + '/getProducts/removecartitems/' + _id); /* This goes back to calling function so I can try to delete from collection*/ } </code>
      RemoveProductFromCart(_id:string){  
    
        alert("show deleted item" + _id);
 return this.http.delete<Cartitems[]>(this.rootUrl + '/getProducts/removecartitems/' + _id);
 
     /* This goes back to calling function so I can try to delete from collection*/
  
 
 
   }

2

Using tap from RxJS and filter instead of splice

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>handleRemoveFromCart(cartItemId: string) {
this.cartService.RemoveProductFromCart(cartItemId).pipe(
tap(() => {
this.cartItems = this.cartItems.filter(item => item._id !== cartItemId);
})
).subscribe();
}
</code>
<code>handleRemoveFromCart(cartItemId: string) { this.cartService.RemoveProductFromCart(cartItemId).pipe( tap(() => { this.cartItems = this.cartItems.filter(item => item._id !== cartItemId); }) ).subscribe(); } </code>
handleRemoveFromCart(cartItemId: string) {
    this.cartService.RemoveProductFromCart(cartItemId).pipe(
      tap(() => {
        this.cartItems = this.cartItems.filter(item => item._id !== cartItemId);
      })
    ).subscribe();
  }

filter creates a new array without the specified carItemId while the tap operator allows you to perform a “side effect”, in this case, deleting the item. Also, RemoveProductFromCart returns void, since there’s no need to return a new array after a delete request.

RxJS – tap

2

The naming convention you are using for your cartitems seems wrong, you usually use $ when the type is an Observable, if that’s a typo from your end and it is indeed an observable, then you have to update the cartItems by sending a new updated array like so:

component.ts

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>@Component({...})
export class CartComponent {
// the cart items data wrapped within an observable
cartItems$!: Observable<CartItem[]>;
//...
// first approach:
onDeleteItem(id: string): void {
this.cartService.RemoveProductFromCart(id)
.pipe(
take(1),
withLatestFrom(this.cartItems$) // grab the current data in the cart items
)
.subscribe(([response, cartItems]: [ResponseService, CartItem[]]) => {
const filtered = cartItems.filter(e => e._id !== id); // remove the deleted item
this.cartItems$.next(filtered); // update the cart items
})
}
// second approach: (There are many actually...)
onDeleteItem2(id: string): void {
this.cartItems$ = this.cartService.RemoveProductFromCart(id)
.pipe(
withLatestFrom(this.cartItems$),
concatMap(([response, cartItems]: [ResponseService, CartItem[]]) => {
const filtered = cartItems.filter(e => e._id !== id)
return of(filtered);
})
)
}
}
</code>
<code>@Component({...}) export class CartComponent { // the cart items data wrapped within an observable cartItems$!: Observable<CartItem[]>; //... // first approach: onDeleteItem(id: string): void { this.cartService.RemoveProductFromCart(id) .pipe( take(1), withLatestFrom(this.cartItems$) // grab the current data in the cart items ) .subscribe(([response, cartItems]: [ResponseService, CartItem[]]) => { const filtered = cartItems.filter(e => e._id !== id); // remove the deleted item this.cartItems$.next(filtered); // update the cart items }) } // second approach: (There are many actually...) onDeleteItem2(id: string): void { this.cartItems$ = this.cartService.RemoveProductFromCart(id) .pipe( withLatestFrom(this.cartItems$), concatMap(([response, cartItems]: [ResponseService, CartItem[]]) => { const filtered = cartItems.filter(e => e._id !== id) return of(filtered); }) ) } } </code>
@Component({...})
export class CartComponent {
  // the cart items data wrapped within an observable
  cartItems$!: Observable<CartItem[]>;
  
  //...

  // first approach:
  onDeleteItem(id: string): void {
    this.cartService.RemoveProductFromCart(id)
     .pipe(
       take(1),
       withLatestFrom(this.cartItems$) // grab the current data in the cart items
      )
     .subscribe(([response, cartItems]: [ResponseService, CartItem[]]) => {
        const filtered = cartItems.filter(e => e._id !== id); // remove the deleted item
        this.cartItems$.next(filtered); // update the cart items
     })
  }

  // second approach: (There are many actually...)
  onDeleteItem2(id: string): void {
     this.cartItems$ = this.cartService.RemoveProductFromCart(id)
       .pipe(
         withLatestFrom(this.cartItems$),
         concatMap(([response, cartItems]: [ResponseService, CartItem[]]) => {
              const filtered = cartItems.filter(e => e._id !== id)
              return of(filtered);
         })
       ) 
  }
}

component.html

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code><!-- This is just an example on how to handle your cart items source -->
<!-- within the template HTML -->
<ng-container *ngIf="cartItems$ | async as items">
<li *ngFor="let item of items">{{ item.name }} - {{ item.price }}</li>
</ng-container>
<!-- If you are using the latest version of Angular, you could do it like this -->
@if (cartItems$ | async; as items) {
@for (item of items; track item) {
<li>{{ item.name }} - {{ item.price }}</li>
}
}
</code>
<code><!-- This is just an example on how to handle your cart items source --> <!-- within the template HTML --> <ng-container *ngIf="cartItems$ | async as items"> <li *ngFor="let item of items">{{ item.name }} - {{ item.price }}</li> </ng-container> <!-- If you are using the latest version of Angular, you could do it like this --> @if (cartItems$ | async; as items) { @for (item of items; track item) { <li>{{ item.name }} - {{ item.price }}</li> } } </code>
<!-- This is just an example on how to handle your cart items source  -->
<!-- within the template HTML -->
<ng-container *ngIf="cartItems$ | async as items">
  <li *ngFor="let item of items">{{ item.name }} - {{ item.price }}</li>
</ng-container>

<!-- If you are using the latest version of Angular, you could do it like this -->
@if (cartItems$ | async; as items) {
  @for (item of items; track item) {
    <li>{{ item.name }} - {{ item.price }}</li>
  }
}

In the first approach, it subscribes manually to the http response from the server and in it, you next it with the updated cart items.

The second one, you don’t subscribe, instead you pipe it and return a final Observable holding the updated cart items.

Additionally, you should also handle the possible scenario of an error with catchError, but I didn’t implemented since I am not sure if you are already doing that in your project.

As a side note, I am not sure why you have 2 cartItems declared in your component, both seems to be of the same type, the only differences are the names, one doesn’t have $ the other one does it which is very confusing.

Maybe try the following:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>handleRemoveFromCart(cartItem: CartItem) {
this.cartService.removeProductFromCart(cartItem._id).subscribe(
() => {
console.log("Product with Id deleted", cartItem._id);
const index = this.cartItems.findIndex(item => item._id === cartItem._id);
if (index > -1) {
this.cartItems.splice(index, 1);
console.log("Item removed from local array");
}
},
(error) => {
console.error('Error removing item from cart:', error);
}
);}
</code>
<code>handleRemoveFromCart(cartItem: CartItem) { this.cartService.removeProductFromCart(cartItem._id).subscribe( () => { console.log("Product with Id deleted", cartItem._id); const index = this.cartItems.findIndex(item => item._id === cartItem._id); if (index > -1) { this.cartItems.splice(index, 1); console.log("Item removed from local array"); } }, (error) => { console.error('Error removing item from cart:', error); } );} </code>
handleRemoveFromCart(cartItem: CartItem) {
this.cartService.removeProductFromCart(cartItem._id).subscribe(
  () => {
    console.log("Product with Id deleted", cartItem._id);
    const index = this.cartItems.findIndex(item => item._id === cartItem._id);
    if (index > -1) {
      this.cartItems.splice(index, 1);
      console.log("Item removed from local array");
    }
  },
  (error) => {
    console.error('Error removing item from cart:', error);
  }
);}

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật