How to remove specific element from Observable<Array<any>>
You can't do it this way since you can't "update" an observable (i.e. it doesn't keep states) but you can react to an event through it.
For your use case, I would leverage the scan
operator and merge two streams into a single one:
- one for the initial loading
- another one for the delete event.
Here is a sample:
let obs = this.http.get('/data').map(res => res.json());
this.deleteSubject = new Subject();
this.mergedObs = obs.merge(this.deleteSubject)
.startWith([])
.scan((acc, val) => {
if (val.op && val.op==='delete') {
var index = acc.findIndex((elt) => elt.id === val.id);
acc.splice(index, 1);
return acc;
} else {
return acc.concat(val);
}
});
To trigger an element deletion, simply send an event on the subject:
this.deleteSubject.next({op:'delete', id: '1'});
See this plunkr: https://plnkr.co/edit/8bYoyDiwM8pM74BYe8SI?p=preview.