0

I was trying to filter my angular material table like this, but it didn't work (probably because it's a Observable).

HTML

 <mat-form-field>
    <mat-label>Search</mat-label>
       <input matInput placeholder="Digite algo a ser apresentado (keyup)="toSearch($event.target)" />
    <mat-icon matSuffix>search</mat-icon>
</mat-form-field>

TS

aplicativos:any = this.aplicativoService.toGetAllAplicativos();
  dataSource = new MatTableDataSource();

  ngOnInit(): void {
    this.dataSource = this.aplicativos;
  }

  toSearch = (search: any) =>
    (this.dataSource.filter = search.value.trim().toLowerCase());

Service:

toGetAllAplicativos() { return this.http.get(`${this.API}/aplicativos`).pipe(take(1)); }

So I changed my code to work like this, and it's working now:

TS

 aplicativos = this.aplicativoService.toGetAllAplicativos();
 dataSource;
 

  ngOnInit(): void {
     this.aplicativos.subscribe(response => {
         this.dataSource = new MatTableDataSource(response);
       })
    }
    
   toSearch(search: any){
      this.dataSource.filter = search.value.trim().toLowerCase();
    }

The question is: do I need to subscribe if I'm using take(1)?

Ruina
  • 401
  • 2
  • 12
Desenv Junior
  • 101
  • 1
  • 1
  • 10
  • First of all, you don't need to `take(1)` when it's a http request. It's 'take(1)'-like by default. – Ivan Nov 12 '21 at 17:48

1 Answers1

2

No, if you use take(1) or first(), you won't need to unsubscribe as it will automatically unsubscribe after the first event received.

More detailed answer here

Tonio
  • 4,082
  • 4
  • 35
  • 60