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

3.6k views Asked by At

I have some cards displayed in the UI.

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

Obviosuly cards will be the Observable of array of type card.

So I have an interface of card lets say it has 3 properties

Id, name, description.

My use case is.

  1. I want to add new card to the observables array and must reflect to array.

  2. I want to delete the card from the observable and must reflect to the template.

  3. I must be able to filter the card baaed on lets say name and must be reflected in the template.

In short all the aperations must be done in the observable as I have used async pipe in the template.

1

There are 1 answers

0
Abolfazl Roshanzamir On BEST ANSWER

to do that you can use map rxjs operator like the following :

  cards$: Observable<Card[]>;

  constructor(private serivce: CardService) { }

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

Add item to the observable array

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

Remove item from the observable array

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

And finally in your 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>