在 Angular 4 中使用过滤器管道

Using Filter Pipe In Angular 4

我在 angular 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;
    });
  }
}

在这种情况下,您的出口是每个数组对象中的另一个对象,因此您需要专门为出口添加一个过滤器,如下所示,

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