rxJS中的管道是什么

rxJS中的管道是什么

本文介绍了rxJS中的管道是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为我有基本概念,但是有些晦涩之处

I think I have the base concept, but there are some obscurities

所以一般来说,这就是我使用可观察的方式:

So in general this is how I use an observable:

observable.subscribe(x => {

})

如果我想过滤数据,我可以使用它:

If I want to filter data I can use this:

import { first, last, map, reduce, find, skipWhile } from 'rxjs/operators';
observable.pipe(
    map(x => {return x}),
    first()
    ).subscribe(x => {

})

我也可以这样做:

import 'rxjs/add/operator/map';
import 'rxjs/add/operator/first';

observable.map(x => {return x}).first().subscribe(x => {

})

所以我的问题是:

  1. 有什么区别?
  2. 如果没有区别,为什么功能管道存在?
  3. 为什么这些功能需要不同的导入?

推荐答案

可点入" (以前的"lettable")运算符是从RxJS 5.5开始的当前和推荐的使用运算符的方式.

The "pipable" (former "lettable") operators is the current and recommended way of using operators since RxJS 5.5.

我强烈建议您阅读官方文档 https://rxjs.dev/guide/v6/pipeable-operators

I strongly recommend you to read the official documentation https://rxjs.dev/guide/v6/pipeable-operators

主要区别在于,使自定义运算符更容易,并且树状结构更好,同时又不更改某些全局Observable对象,如果两个不同的当事方想要创建同名运算符,则可能会导致冲突.

The main difference is that it's easier to make custom operators and that it's better treeshakable while not altering some global Observable object that could possible make collisions if two different parties wanted to create an operator of the same name.

为每个运算符'rxjs/add/operator/first'使用单独的import语句是制作较小的应用程序包的一种方法.通过仅导入所需的运算符而不是整个RxJS库,可以显着减小总包大小.但是,编译器无法知道是否导入了'rxjs/add/operator/first',因为您确实在代码中需要使用'rxjs/add/operator/first',或者只是在重构代码时忘记将其删除.这是使用可插值运算符的优势之一,可自动忽略未使用的导入.

Using separate import statement for each operator 'rxjs/add/operator/first' was a way to make smaller app bundles. By importing only operators you need instead of the entire RxJS library you can significantly reduce the total bundle size. However the compiler can't know if you imported 'rxjs/add/operator/first' because you really need it in you code or you just forgot to remove it when refactoring your code. That's one of the advantages of using pipable operators where unused imports are ignored automatically.

这篇关于rxJS中的管道是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 02:37