简体   繁体   English

RxJS / Angular Observables 使用 1 个还是多个管道?

[英]RxJS / Angular Observables use 1 or multiple pipes?

Having the following (just a quick example):有以下(只是一个简单的例子):

observable.pipe(map( s => s.anything ))
          .pipe(filter(t => t > 5))
          .pipe(map( t => t+5))
          .subscribe( XXX )

Why should I use 1 pipe instead?为什么我应该使用 1 个管道?

    observable.pipe(
                   map( s => s.anything ), filter(t => t > 5),map( t => t+5))
              .subscribe( XXX )

To me, the code is more nice and readable in the first case.对我来说,第一种情况下的代码更漂亮、更易读。 But no idea if that affects the behaviour anyway.但不知道这是否会影响行为。

You should use a single pipe for that purpose.为此,您应该使用单个管道。 Having multiple pipes will serve no purpose or benefit, as the usage of pipes is to combine RxJS functional operators into a single chain.拥有多个管道没有任何意义或好处,因为管道的用途是将 RxJS 功能运算符组合成一个链。

In order to make it more readable, you can do something like this, instead of having all the operators on 1 single line of code.为了使其更具可读性,您可以执行以下操作,而不是将所有运算符都放在 1 行代码中。

observable
  .pipe(
    map(s => s.anything ),
    filter(t => t > 5),
    map(t => t+5)
  ).subscribe(res => {
    // do the rest
});

The official Angular guide has a good summary on the usage of pipes and other operators. Angular 官方指南对管道和其他运算符的使用有很好的总结。 You may read up more about it over here .你可以在这里阅读更多关于它的信息 You should read up about pipeable operators over here as well.您也应该在这里阅读有关可管道操作符的信息。

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

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