简体   繁体   English

angular 中的 Rxjs 滤波器运算符

[英]Rxjs filter operator in angular

We have filter operator in Rxjs to filter the emitted items by the observables based on a condition.我们在 Rxjs 中有过滤器运算符,用于根据条件过滤可观察对象发出的项目。

Of(1,2,3).pipe( filter(item = item >= 2) )

So here we can filter the emitted numbers that are >=2.所以在这里我们可以过滤 >=2 的发射数字。 We get (2,3)我们得到 (2,3)

I can do the filtering on the same condition after subscribing to the items.订阅项目后,我可以在相同的条件下进行过滤。 Of(1,2,3).subscribe((items)=>{ items = items.filter(item=>item>=2); } )

If this can be done after subscribing, what is the real significance of the operator filter in Rxjs?如果订阅后可以做到这一点,那么Rxjs中的算子过滤器的真正意义是什么?

One possible reason is that filtering before subscription allows you to avoid emitting values to subscribers if the result of the filter isn't different from the previous emit.一个可能的原因是,如果过滤器的结果与之前的发射没有不同,那么订阅前的过滤允许您避免向订阅者发射值。 You could accomplish this with distinctUntilChanged() .您可以使用distinctUntilChanged()来完成此操作。

Here's filtering after subscription (notice the Observable emits twice).这是订阅后的过滤(注意 Observable 发出两次)。

const source = new Subject<number[]>();

source.asObservable().subscribe(items => {
    console.log(items.filter(i => i >= 2));
});

source.next([1, 2, 3, 4]);
// Logs: [2, 3, 4]

source.next([-1, 1, 2, 3, 4]);
// Logs: [2, 3, 4]

Here's filtering before subscription (notice the Observable only emits once).这是订阅前的过滤(注意 Observable 只发出一次)。

const source = new Subject<number[]>();

source.asObservable().pipe(
  filter(items => items.filter(i => i >= 2)),
  distinctUntilChanged()
).subscribe(items => console.log);

source.next([1, 2, 3, 4]);
// Logs: [2, 3, 4]

source.next([-1, 1, 2, 3, 4]);
// Doesn't log anything because the result
// of pipe(filter()) wasn't different from
// the previous value, so the observable
// didn't emit.

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

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