[英]angular rxjs pipe remove element from array
I have a service with a delete function.我有一个带有删除功能的服务。 The delete function will call an api and it will return true or false.
delete 函数将调用一个 api,它将返回 true 或 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 :我有一个 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.
我首先想到过滤器(在 switchmap 之后)排除具有我提供的 id 的元素,然后发出新数组,但后来我意识到,过滤器没有订阅 this.items 数组。
What would be the best approach to do this?这样做的最佳方法是什么?
I don't know you other code, for example where this.items
coming from, why do you publish updated items to onItemDeleted
.我不知道你的其他代码,例如
this.items
来自哪里,你为什么将更新的项目发布到onItemDeleted
。 But I would probably: a) pass this.items
to delete method also like delete(id, items)
because on the time when response will arrive, you don't know what will happen with this.items
;但我可能会:a) 将
this.items
传递给 delete 方法也像delete(id, items)
因为在响应到达时,您不知道this.items
会发生什么; b) that thing within the map, move to separate function, that will be removeById(items, id)
; b) 地图中的那个东西,移动到单独的函数,这将是
removeById(items, id)
; c) simplify pipe
. c) 简化
pipe
。 Like this:像这样:
private items = [];
onItemDeleted = new Subject<any>();
removeById(fromItems, id) {
const index1 = fromItems.findIndex((element) => {
return element.id === id;
});
if (index1 >= 0 ) {
fromItems.splice(index1,1);
}
return fromItems;
}
// who ever calls this, should provide copy of items also
// then you will be kinda protected from concurrent
// modification, when http response complete, but this.items
// is completely different, from when http request started
delete(fromItems, id:number): Observable<any> {
return this.http.delete('http://my.api.com/item/' + id)
.pipe(
switchMap(checkServerSuccessResponse),
map(data => this.removeById(fromItems, id)),
tap(items => this.onItemDeleted.next(items)),
catchError(returnFalse),
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.