首页 > 解决方案 > Angular Take 操作员需要退订吗?

问题描述

我试图像这样过滤我的角度材料表,但它不起作用(可能是因为它是一个 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());

服务

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

所以我改变了我的代码,让它像这样工作,现在它正在工作:

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

问题是:如果我使用 take(1),我需要订阅吗?

标签: angularrxjs

解决方案


不,如果您使用take(1)or first(),则不需要取消订阅,因为它会在收到第一个事件后自动取消订阅。

更详细的答案在这里


推荐阅读