代码之家  ›  专栏  ›  技术社区  ›  ItFreak

角7滤波器阵列

  •  1
  • ItFreak  · 技术社区  · 7 年前

      private json: JsonResponseDTO;
    
      constructor(private dtoService: PoolDTOServiceService) {
      }
    
      ngOnInit() {
        this.dtoService.setJsonResponse();
        this.getPool();
      }
    
      getPool() {
        this.json = this.dtoService.jsonResponse;
      }
    

    json
    我希望能够“删除”我的搜索条件,因此最初的方法是:

      private json: JsonResponseDTO;
    private filterJson: JsonResponseDTO;
    
      constructor(private dtoService: PoolDTOServiceService) {
      }
    
      ngOnInit() {
        this.dtoService.setJsonResponse();
        this.getPool();
      }
    
      getPool() {
        this.json = this.dtoService.jsonResponse;
        this.filterJson = this.json;
      }
    
      filter(filterCriteria: String) {
        this.filterJson = this.json;
        this.filterJson.pools.filter((element) => element.name === filterCriteria);
      }
    

    然后绑好 filterJson
    有没有更干净的方法? 我希望避免每次“删除”过滤名称时都请求新的JSON,因为获取数据的时间非常昂贵。

    2 回复  |  直到 7 年前
        1
  •  3
  •   Akshay Rajput    7 年前

    您可以使用管道进行过滤,这样会更干净,只需在*ngFor指令前面添加管道即可。

    @Pipe({
      name: 'filter'
    })
    export class FilterPipe implements PipeTransform {
      transform(value: any, field: string, input: string) {
        if (input !== undefined && input.length >= 2) {
          input = input.toLowerCase();
          if (typeof value[0] === 'string') {
            return value.filter(function(el: any) {
              return el.toLowerCase().indexOf(input) > -1;
            });
          }
          return value.filter(function(el: any) {
            return el[field].toLowerCase().indexOf(input) > -1;
          });
        }
        return value;
      }
    }
    

    添加此管道,并在需要筛选的HTML中添加

    <div *ngFor="let val of filterJson | filter: "filterCriteria""> </div>
    

        2
  •  1
  •   Dhananjai Pai    7 年前
    filter(filterCriteria: String) {
        this.filterJson = {...this.json, pools: pools.filter((element) => element.name === filterCriteria);
    }
    

    通过使用spread并如上所述更改pools属性,您可能会编写得更干净一些。

    我假设您应该保留原始“this.json”的缓存副本,以备过滤器重置时使用。