如何从Observable< Array< any>>中删除特定元素 [英] How to remove specific element from Observable<Array<any>>

查看:65
本文介绍了如何从Observable< Array< any>>中删除特定元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个地方数组的Observable:

There is an Observable of the array of places:

places: Observable<Array<any>>;

在模板中,它与异步管道一起使用:

In template it used with the async pipe:

<tr *ngFor="let place of places | async">
  ...
</tr>

在执行一些用户操作后,我需要从此数组中删除具有特定ID的位置。我的代码中有这样的东西,但它不起作用:

After some user actions I need to remove the place with specific id from this array. I have something like this in my code, but it doesn't work:

deletePlace(placeId: number): void {
  this.apiService.deletePlace(placeId)
  .subscribe(
    (res: any) => {
      this.places
        .flatMap((places) => places)
        .filter((place) => place.id != placeId);
    }, 
    (err: any) => console.log(err)
  );    
}  

你能帮我解决这个问题吗?

Can you help me with this?

推荐答案

你不能这样做,因为你不能更新一个observable(即它不保持状态)但你可以对一个事件作出反应通过它。

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.

对于您的用例,我将利用 scan 运算符并将两个流合并为一个:

For your use case, I would leverage the scan operator and merge two streams into a single one:


  • 一个用于初始加载

  • 另一个用于删除事件。

以下是一个示例:

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'});

请参阅此plunkr: https://plnkr.co/edit/8bYoyDiwM8pM74BYe8SI?p=preview

See this plunkr: https://plnkr.co/edit/8bYoyDiwM8pM74BYe8SI?p=preview.

这篇关于如何从Observable&lt; Array&lt; any&gt;&gt;中删除特定元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆