简体   繁体   English

如何使用来自 rxjs 的过滤器

[英]How to use filter from rxjs

I am filtering an array of JSON objects, I want to return the found object based on the passed in id argument.我正在过滤一个 JSON 对象数组,我想根据传入的id参数返回找到的 object 。

 getClient(id) {
   return this.http.get<any>(' http://localhost:3000/clients')
    .pipe(
      filter(client => client.idNumber === id)
    );
 }

The observer to the above is not triggered and does not receive any data.上面的观察者没有被触发,也没有收到任何数据。

  getClient(id)
  .subscribe(
   (data) => {
     // nothing here
   }
  )

The below implementation of getClient achieves what I want. getClient的以下实现实现了我想要的。

 getClient(id) {
   return this.http.get<any>(' http://localhost:3000/clients')
    .pipe(
      map(clients => clients.find(client => client.idNumber === id))
    );
 }

I would like to understand, am I using the filter operator the wrong way?我想了解,我是否以错误的方式使用过滤器运算符? And how is my usage different from the one here我的用法与这里的用法有何不同

Correct, you are using the rxjs filter operator the wrong way.正确,您以错误的方式使用 rxjs filter运算符。

Per the docs :根据文档

Filter items emitted by the source Observable by only emitting those that satisfy a specified predicate.通过仅发出满足指定谓词的项来过滤源 Observable 发出的项。

In your example, the client value that is getting sent to filter is the array of clients that your http request returned.在您的示例中,发送到过滤器的client值是您的 http 请求返回的客户端数组。 Then, you are saying "don't emit anything unless client (which is actually an array and has no "idNumber" property is equal to id , which will always be false because unefined !== number然后,你说“不要发出任何东西,除非client (它实际上是一个数组并且没有“idNumber”属性等于id ,这将永远是错误的,因为unefined !== number

If you want to modify the, you need to use the map operator.如果要修改的话,需要使用map算子。 The map operator takes what the observable emits, lets you do something (like filter or find in the array), and then return that modified data to subscribers. map 运算符获取可观察对象发出的内容,让您执行某些操作(例如过滤或在数组中查找),然后将修改后的数据返回给订阅者。

Also, if you type your responses property, TypeScript will warn you about this.此外,如果您键入您的响应属性,TypeScript 会就此发出警告。 Instead of this.http.get<any> use this.http.get<Client[]> or some more appropriate type.而不是this.http.get<any>使用this.http.get<Client[]>或更合适的类型。 You would be able to see at compile time that Client[] has no property idNumber .您将能够在编译时看到Client[]没有属性idNumber

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM