【问题标题】:How to create a input filter for a angular table?如何为角度表创建输入过滤器?
【发布时间】:2021-03-31 14:51:26
【问题描述】:

我正在尝试在 Angular 11 项目中实现一个带有输入过滤器的表。该表由 SERVICE 填充:

export class Service{
 url='myUrl';

 http; 

 constructor(private http:HttpClient){
  this.http=http
 } 

 loadAll(): Observable<Author[]> {
  return this.http.get<Author[]>(this.url)
}

在我的组件中,我有一个变量“filteredAuthors$”,它将代表表中显示的所有数据。

export class MyComponent{
 authors$:Observable<Author[]>
 filteredAuthors$:Observable<Author[]>

 //form that receive the input filter
 filterForm:FormControl

 constructor(private service:Service){
  this.authors$=service.loadAll()

  filterForm=new ForControl('')

  this.filteredAuthors$=filterForm.valueChanges.pipe(
   startWith('').withLatestFrom(this.authors$),
   map(
    ([typedValue, authors])=>!typedValue ? authors : 
     authors.filter(author=>author.name.includes(typedValue))
)))}}

使用此代码,我总是以 0 行开始我的表格,并且在输入内容后,过滤器工作得很好。另一个奇怪的事情是,当我用“of”方法创建的模拟可观察对象替换我的服务时,表从所有行开始,并在过滤器中的第一个输入之后被过滤。我没有看到什么?作者类型是:

export type Author={
 id:string,
 name:string
}

【问题讨论】:

  • 是的,但是服务正在从我的 json-server 接收数据。当我调试时,我看到我的“authors$”observable 已经收到了这些值,但它没有映射到filteredAuthors$ observable。在我在 filterForm 中输入内容之前,filteredAuthors$ 不会发出任何值。
  • 当你“调试”时,你会做与of 完全相同的事情——你会跳过异步副作用,因为你在通常程序不会停止的地方“暂停执行”。调试异步代码时需要小心。
  • withLatestFrom 可能会阻止流的开始,但这就是我使用“startWith”运算符的原因。
  • 不,它是排在第二位的,并且也会阻止人工发出的值(来自 startWith)。请记住,这是一个管道 - 没有跳过运算符。
  • 您可以在此处查看startsWith 在管道中的位置stackblitz.com/edit/rxjs-m8gjd8?file=index.ts

标签: angular filter observable angular-reactive-forms reactive


【解决方案1】:
  1. of 是同步的,因此您将跳过延迟的 observable 的所有可能的异步副作用——比如网络调用。
  2. withLatestFrom 将阻塞直到给定 observable 发射事件。因此,直到 authors$ 完成(假设是一个网络调用),管道下的处理被抑制。 (这里的第二个例子证实了https://www.learnrxjs.io/learn-rxjs/operators/combination/withlatestfrom

【讨论】:

  • 好吧,如果异步是问题所在,我可以等到我的服务获取数据然后保留流吗?
  • 是的,例如获取作者,以及switchMap对输入值的更改。此时您将拥有所有作者 - 可以存储为字段。
  • 在研究了同步与异步 observables 15 个小时后,我终于明白了使用“of”(同步)和 http.get(异步)创建的 observable 的区别。你的回答让我明白了我正在做的根本错误。谢谢!
猜你喜欢
  • 1970-01-01
  • 2015-04-17
  • 2022-11-07
  • 2013-03-08
  • 2015-09-14
  • 1970-01-01
  • 1970-01-01
  • 2022-08-23
  • 1970-01-01
相关资源
最近更新 更多