【问题标题】:Using Filter Pipe In Angular 4在 Angular 4 中使用过滤器管道
【发布时间】:2018-06-16 11:17:54
【问题描述】:

我在 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
          },
        }
      ]
    }
  ]
}

过滤管

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

【问题讨论】:

  • 你的 JSON 没有那个值
  • @Sajeetharan。请帮忙:)
  • 发布完整的 JSON
  • @Sajeetharan。这是我完整的 JSON。我只能搜索管理员名称和电子邮件,但不能搜索网站名称、描述和角色名称

标签: angular filter angular2-services angular-pipe


【解决方案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

【讨论】:

  • 谢谢 它适用于出口名称,角色名称怎么样?
  • 你需要为角色添加另一个过滤器检查更新的演示
  • 角色名有误。无法读取未定义的属性“名称”
  • 在哪里?我没看到
  • 查看附件。
猜你喜欢
  • 2017-11-29
  • 2018-02-24
  • 1970-01-01
  • 2017-10-07
  • 1970-01-01
  • 1970-01-01
  • 2020-07-26
  • 2018-02-02
相关资源
最近更新 更多