在Angular 4中使用过滤管

时间:2018-01-07 03:12:30

标签: angular filter angular2-services angular-pipe

我在角度4应用程序中使用过滤管道。但是我有一个问题,因为我在数组内部进行过滤,但也在该数组内部进行过滤。所以我找不到那个特定的名字......因为我只能找到第一个数组但不能找到内部数组。这是我的JSON响应和下面的管道代码。在这里,我只能搜索"admin name and email"但我无法搜索"Outlet name, address AND Role name"

  

JSON

{
  "token": "eyefqffiwqnrfoqif",
  "users": [
    {
      "id": 1,
      "name": "Admin",
      "email": "admin@yahoo.com",
      "created_at": "2018-01-05 07:17:41",
      "updated_at": "2018-01-05 09:17:41",
      "outlet": {
      "id": 1,
      "name": "Sarawak Energy Berhad",
      "address": "Kuching City",
      "contact_number": "1300-88-3111",
      "created_at": "2018-01-05 10:17:44",
      "updated_at": "2018-01-05 10:17:44"
    },
      "roles": [
        {
          "id": 1,
          "name": "Admin",
          "created_at": "2018-01-05 10:17:40",
          "updated_at": "2018-01-05 10:17:40",
          "pivot": {
            "model_id": 1,
            "role_id": 1
          },
        }
      ]
    }
  ]
}
  

FILTER PIPE

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'search'
})
export class SearchPipe implements PipeTransform {
  transform(items: any, term: any): any {
    if (term === undefined) return items;

    return items.filter(function(item) {
      for(let property in item){
        if (item[property] === null){
          continue;
        }
        if(item[property].toString().toLowerCase().includes(term.toLowerCase())){
          return true;
        }
      }
      return false;
    });
  }
}

1 个答案:

答案 0 :(得分:1)

在这种情况下,您的插座是每个阵列对象内的另一个对象,因此您需要为插座专门添加一个过滤器,如下所示,

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'filter'
})
export class FilterPipe implements PipeTransform {
 transform(items: any, term: any): any {
    if (term === undefined) return items;

    return items.filter(function(item) {
      for(let property in item){

        if (item[property] === null){
          continue;
        }
        if(item[property].toString().toLowerCase().includes(term.toLowerCase())){
          return true;
        }
         if(property ='outlet'){
           if(item[property].name.toString().toLowerCase().includes(term.toLowerCase())){
           console.log(item[property].name);
          return true;
         }

        }
         if(property ='roles'){
         if (item[property].filter(e => e.name === term.toLowerCase()).length > 0) {
          return true;
         }

        }
       }
      return false;
    });
  }

}

<强> DEMO STACKBLITZ