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)
)
)
)
);
}
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) => {});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With