I have a service with a delete function. The delete function will call an api and it will return true or false. When true, I will lookup the index in my array, splice it and return the new array. So for example
private items = [];
onItemDeleted = new Subject<any>();
delete(id:number): Observable<any> {
return this.http.delete('http://my.api.com/item/' + id)
.pipe(
switchMap(checkServerSuccessResponse),
map(data => {
const index1 = this.items.findIndex((element) => {
return element.id === id;
});
if (index1 >= 0 ) {
this.items.splice(index1,1);
}
this.onItemDeleted.next(this.items);
return this.items;
}
),
catchError(returnFalse),
);
}
I have a helper for the switchmap :
export function checkServerSuccessResponse(data: Response): Observable<any> {
return (data && data['success'] === true) ? of(data) : throwError("server responded false");
}
Although this works, I have a feeling the map section can reformatted. I first thought of filter (after the switchmap) to exclude the element with the id I've supplied, then emit the new array, but then I realised, the filter is not subscribed to the this.items array.
What would be the best approach to do this?
this.itemscoming from, why do you publish updated items toonItemDeleted. But I would probably: a) passthis.itemstodeletemethod also likedelete(id, items)because on the time when response will arrive, you don't know what will happen withthis.items; b) that thing within themap, move to separate function, that will beremoveById(items, id); c)pipewill becomeswitchMap(checkServerSuccessResponse), map(removeById), tap(onItemDeleted.next), catchError(returnFalse)(calls abbreviated to fit to this comment).