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

查看:12
本文介绍了如何从 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(即它不保持状态)但你可以对一个 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<Array<any>> 中删除特定元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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