Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete item from observable array? [closed]

Tags:

angular

rxjs

I have observable:

private events$: BehaviorSubject<IEvent[]> = new BehaviorSubject<IEvent[]>([]);

I add data to this observer using:

 this.events$.next([{"id": 1}, {"id": 2}, {"id": 3}]);

How to remove item from observable array from template??

<div *ngFor="let item in events | async">
   <span (click)="detele(item)">Delete</span>
</div>

I have tried to delete using this:

  public delete(event: IEvent): void {
    this.confirm
      .open({})
      .pipe(
        filter(Boolean),
        concatMap(() => this.eventService.delete(event))
      )
      .subscribe((updated) => this.eventService.next(updated));
  }

And service is:

  public delete(event: IEvent): Observable<any> {
    return this.eventsService
      .delete(event)
      .pipe(
        concatMap(() =>
          this.events$.pipe(
            map((events: IEvent[]) =>
              events.filter((e) => e.idEvent !== event.idEvent)
            )
          )
        )
      );
  }

1 Answers

You can't delete an item from the Observable, you have to emit a new value without the deleted item. A method in your component could look like this:

delete(item) {
  // Get current items from the BehaviorSubject.
  const currentItems = this.events$.getValue();
  // Use the id of the argument item to remove it from the currentItems.
  const itemsWithoutDeleted = currentItems.filter(({id}) => id !== item.id));
  // Emit the new array.
  this.events$.next(itemsWithoutDeleted);
}

Edit after you updated your post:

Your problem is that you don't update the events$ subject in your delete method, you could e.g. use tap here or use the subscribe method:

public delete(event: IEvent): void {
    this.confirm
      .open({})
      .pipe(
        filter(Boolean),
        concatMap(() => this.eventService.delete(event))
        // Use tap here to update the events$.
        tap((items) => {
          this.events$.next(items);
        })
      )
      .subscribe((response) => {});
  }
like image 126
code-gorilla Avatar answered Jun 01 '26 07:06

code-gorilla



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!