【问题标题】:Async pipe with Search custom pipe带有搜索自定义管道的异步管道
【发布时间】:2020-03-23 11:08:47
【问题描述】:

我有一个可观察的数据源,因为我从我的 API 中提取数据。 我想通过文本搜索数据并过滤它:

这里有我的 Pipe.ts:

@Pipe({
  name: 'filterText'
})
export class FilterTextPipe implements PipeTransform {

  transform(values, searchTerm): any {

      if (!values || !searchTerm) {
          return _.get(values, '_value', '');
      }

      return values._value.filter( item =>
         item.provider_business_name.toLowerCase().indexOf(searchTerm.toLowerCase()) !== -1
      );

  }

}

这里有我的模板:

<mat-card class="card-provider m-2 p-2" *ngFor="let provider of obs | filterText:searchText | async" />

这也是我的component.ts:

@ViewChild(MatPaginator, {static: true}) paginator: MatPaginator;
    dataSource;
    searchText;
    obs: Observable<any>;

    constructor(
        private _providersService: ProvidersService,
        private dialog: MatDialog,
        private changeDetectorRef: ChangeDetectorRef
    ) { }

    ngOnInit() {
        this.changeDetectorRef.detectChanges();
        this.getProviders();
    }

    getProviders() {
        this._providersService.getAllProviders().subscribe(
            data => {
                this.dataSource = new MatTableDataSource(data);
                this.dataSource.paginator = this.paginator;
                this.obs = this.dataSource.connect();
            }
        );
    }

我这样做是因为我需要对卡片元素进行分页,但我无法将分页器和 FilterPipe 两者结合起来。

非常感谢!

【问题讨论】:

    标签: angular asynchronous pipe angular8


    【解决方案1】:

    Nvm 我找到了一个解决方案,我不知道它是否是最“干净”的方式,但它有效!

    我在 Pipe 中删除了观察者的属性调用:

    管道.ts:

     @Pipe({
          name: 'filterText'
        })
        export class FilterTextPipe implements PipeTransform {
    
          transform(values, searchTerm): any {
    
              if (!searchTerm) {
                  return values;
              }
    
              return values.filter( item =>
                 item.provider_business_name.toLowerCase().indexOf(searchTerm.toLowerCase()) !== -1
              );
    
          }
    
        }
    

    我的模板如下所示:

    <mat-card class="card-provider m-2 p-2" *ngFor="let provider of obs | async | filterText:searchText" >
    

    【讨论】:

    • 请注意,通常不建议将管道用于过滤操作,因为它们经常运行 - 请参阅 Angular 文档以获取更多信息
    猜你喜欢
    • 2019-04-07
    • 1970-01-01
    • 2019-12-14
    • 1970-01-01
    • 2018-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多