通过添加、过滤或删除项目来更新数组的 Rxjs observable

Update Rxjs observable of array by adding ,filtering or deleting items

我在 UI 中显示了一些卡片。

<div *ngFor="let item of cards | async">...</div>

显然 cards 将是类型 card 数组的 Observable。

所以我有一个卡片界面可以说它有 3 个属性

ID、姓名、描述。

我的用例是。

  1. 我想将新卡片添加到 observables 数组并且必须反映到数组。

  2. 我想从observable中删除卡片,必须反映到模板中。

  3. 我必须能够过滤以名称为基础的卡片,并且必须反映在模板中。

简而言之,所有操作都必须在可观察对象中完成,因为我在模板中使用了异步管道。

要做到这一点,您可以使用 map rxjs 运算符,如下所示:

  cards$: Observable<Card[]>;

  constructor(private serivce: CardService) { }

  ngOnInit(): void {
    this.cards$ = this.serivce.getCards();
  }

将项目添加到可观察数组

  // add item with id=6
  addItemToObservable() {
    this.cards$ = this.cards$.pipe(map(data => {
      return [...data, { id: 6, name: 'name-6', description: "description-6" }]
    }))
  }

从可观察数组中删除项目

  removeItemFromObservable({id}) {
    this.cards$ = this.cards$.pipe(map(data => {
      return data.filter(item => item.id !== id)
    }))
  }

最后在你的 Html 中:

<ng-container *ngIf="(cards$ | async) as cards">
  <table>
    <tr *ngFor="let item of cards">
      <td>{{item.id}}</td>
      <td>{{item.name}}</td>
      <td>{{item.description}}</td>
      <td>
         <button type="button" (click)="removeItemFromObservable(item)">
              Remove
          </button>
      </td>
    </tr>
  </table>
</ng-container>


<button type="button" (click)="addItemToObservable()">
  Add
</button>