Angular4中搜索筛选器的管道不工作

Angular4中搜索筛选器的管道不工作,angular,typescript,angular-pipe,Angular,Typescript,Angular Pipe,我是Angular4的新手。我正在处理筛选器。我需要显示输入搜索框中输入的搜索项。为此,我使用管道进行筛选。但它不起作用。下面是我的代码: 从'@angular/core'导入{Pipe,PipeTransform}; @烟斗({ 名称:“searchFilter”, 纯:假 }) 导出类SearchFilterPipe实现PipeTransform{ 转换(项:任意[],项):任意{ console.log(“术语”,术语); 回报期 ?items.filter(item=>item.tit

我是Angular4的新手。我正在处理筛选器。我需要显示输入搜索框中输入的搜索项。为此,我使用管道进行筛选。但它不起作用。下面是我的代码:

从'@angular/core'导入{Pipe,PipeTransform};
@烟斗({
名称:“searchFilter”,
纯:假
})
导出类SearchFilterPipe实现PipeTransform{
转换(项:任意[],项):任意{
console.log(“术语”,术语);
回报期
?items.filter(item=>item.title.indexOf(term)!=-1)
:项目;
}
}

新收藏

在几分钟内购买您想要的东西

快速查看
{{data.name} 价格{{数据.常规价格}
添加到购物车



您应该尝试以下方法

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

@Pipe({
 name: 'searchFilter',
 pure: false
}) 
export class SearchFilterPipe implements PipeTransform {

transform(items: any, term:string): any {
 if(items.length === 0 || term === ''){
    return items;
 }
 const resultArray = [];
 for(const item of items) {
   if(item.title == term){
      resultArray.push(item);
   }
  }
  return resultArray;
}//end of pipe
默认情况下,
pure
为true。这意味着除非过滤器输入不被更改,否则不会触发管道。但如果您输入'pure:false',则每当组件中的数据发生更改时,都会触发相应的筛选器,但这可能会影响性能,因为很多时候筛选器都会触发。
我认为这可能会对您有所帮助。

这主要发生在分页管道结果干扰搜索管道时。我通过存储搜索管道的初始数组解决了这个问题

解决方案1

  storedArray:Array<any> = [];
  transform(value: any, opt?: opt): any {
  //If stored Array length is 0 then it means this is the first time
   if(this.storedArray.length == 0){
   this.storedArray = value;
   }
   /*You search filter code comes here which filters stored array not the value that 
   comes through pipe*/ 
   return this.storedArray.filter((item) => {
   //Your logic
    });
   }

storedArray:Array,它使用单个管道进行搜索和分页。这将解决影响搜索结果的分页结果。

控制台中有任何错误吗?您解决问题了吗?
 //This will update whenever data is more than the stored data
 if(this.storedArray.length < values.length){
   this.storedArray = value;
   }