嗨,我正在构建一个类似 stackoverflow 的小型论坛,并且正在尝试为我的线程标题实现一个简单的文本过滤器。
我最近开始学习 rxjs 和管道,所以这是我到目前为止提出的 2 个问题
- 我不确定我应该使用哪种方法来解析标题,我目前正在使用 string.include() 但它不能正常工作(例如,如果我输入 who,那么“how”显示,如果我输入“how”然后“谁”显示...
 
更新:到目前为止,主要错误似乎是管道只收到第一个字母......但不知道是什么原因造成的。
- 我正在使用纯管道,并且属性通过主题传递给它,不确定这是否是最佳实践方式...
 
https://plnkr.co/edit/VViLYFd5oFTwNqP9eoZi?p=preview
感谢您的帮助和建议
零件
@Component({
  selector: 'dashboard-main',
  pipes:[FilterTitle],
  template:`
  <input type="text" id="title" [(ngModel)]="binding" (keyup)="trigger()">
  <h3>{{binding}}</h3>
  <hr>
  <h3>{{testText}}</h3>
<hr>
<ul>
<li *ngFor="#thread of threadlist | filterTitle:testText">{{thread.title}}</li>
</ul>
  `
})
export class DashboardMainComponent implements OnInit{
  binding:string='Input';
  text$:Subject<string> = new Subject<string>();
  testText:string="";
  ngOnInit():any {
    this.text$.debounceTime(500).distinctUntilChanged().subscribe( text => this.setText(text))
  }
  trigger(){
    this.text$.next(this.binding);
  }
  setText(text:string){
    console.log(text);
    this.testText = text;
  }
  threadlist=[
    {
      title:'Who are you?'
    },
     {
      title:'How are you?'
    },
     {
      title:'Where are you?'
    }
    ]
}
管道
@Pipe({
  name:'filterTitle',
})
export class FilterTitle implements PipeTransform{
    transform(array:any[], [search]):any {
      if(search ===''){
        return array
      }
      return array.filter(thread => {
        return thread.title.includes(search)
      })
    }
}