gpt4 book ai didi

angular - 在 Angular 4 中使用过滤器管道

转载 作者:太空狗 更新时间:2023-10-29 19:27:09 25 4
gpt4 key购买 nike

我在我的 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

关于angular - 在 Angular 4 中使用过滤器管道,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48134013/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com