[英]Best way to import Observable from rxjs
In my angular 2 app I have a service that uses the Observable
class from the rxjs
library. 在我的angular 2应用程序中,我有一个使用rxjs
库中的Observable
类的服务。
import { Observable } from 'rxjs';
At the moment I am just using Observable
so that I can use the toPromise()
function. 目前我只使用Observable
以便我可以使用toPromise()
函数。
I read in another StackOverflow question somewhere that importing in this way and also importing from rxjs/Rx
will import a whole lot of unnecessary stuff from the rxjs
library that will increase the page load times and/or the code base. 我在另一个StackOverflow问题中读到,以这种方式导入并从rxjs/Rx
导入将从rxjs
库导入大量不必要的东西,这将增加页面加载时间和/或代码库。
My question is, what is the best way to import Observable
so I can use the toPromise()
function without having to import everything else? 我的问题是,导入Observable
的最佳方法是什么,所以我可以使用toPromise()
函数而不必导入其他所有内容?
It got simplified with newer version of rxjs . 它使用较新版本的rxjs进行了简化。
import {map} from 'rxjs/operators';
import {Observable,of, from } from 'rxjs';
Instead of chaining we need to pipe . 而不是链接我们需要管道。 For example 例如
Old syntax : 旧语法:
source.map().switchMap().subscribe()
New Syntax: 新语法:
source.pipe(map(), switchMap()).subscribe()
Note: Some operators have a name change due to name collisions with JavaScript reserved words! 注意:由于与JavaScript保留字的名称冲突,某些运算符的名称发生了变化! These include: 这些包括:
do
-> tap
, do
- > tap
,
catch
-> catchError
catch
- > catchError
switch
-> switchAll
switch
- > switchAll
finally
-> finalize
finally
- > finalize
I am writing this answer partly to help myself as I keep checking docs everytime I need to import an operator . 我写这个答案部分是为了帮助自己,因为我每次需要导入操作员时都会继续检查文档。 Let me know if something can be done better way. 如果可以做得更好的话,请告诉我。
import { Rx } from 'rxjs/Rx'
; 1) import { Rx } from 'rxjs/Rx'
; This imports the entire library. 这会导入整个库。 Then you don't need to worry about loading each operator . 然后,您无需担心加载每个运算符。 But you need to append Rx. 但你需要附加Rx。 I hope tree-shaking will optimize and pick only needed funcionts( need to verify ) As mentioned in comments , tree-shaking can not help. 我希望树摇动会优化并只挑选所需的功能(需要验证)正如评论中所提到的,树木震动无法帮助。 So this is not optimized way. 所以这不是优化方式。
public cache = new Rx.BehaviorSubject('');
Or you can import individual operators . 或者您可以导入单个运算符。
This will Optimize your app to use only those files : 这将优化您的应用程序以仅使用这些文件 :
import { _______ } from 'rxjs/_________';
2) import { _______ } from 'rxjs/_________';
This syntax usually used for main Object like Rx
itself or Observable
etc., 此语法通常用于主要对象,如Rx
本身或Observable
等,
Keywords which can be imported with this syntax 可以使用此语法导入的关键字
Observable, Observer, BehaviorSubject, Subject, ReplaySubject
import 'rxjs/add/observable/__________';
3) import 'rxjs/add/observable/__________';
Update for Angular 5 Angular 5的更新
With Angular 5, which uses rxjs 5.5.2+ 使用Angular 5,它使用rxjs 5.5.2+
import { empty } from 'rxjs/observable/empty';
import { concat} from 'rxjs/observable/concat';
These are usually accompanied with Observable directly. 这些通常直接附带Observable。 For example 例如
Observable.from()
Observable.of()
Other such keywords which can be imported using this syntax: 可以使用以下语法导入的其他此类关键字:
concat, defer, empty, forkJoin, from, fromPromise, if, interval, merge, of,
range, throw, timer, using, zip
import 'rxjs/add/operator/_________';
4) import 'rxjs/add/operator/_________';
Update for Angular 5 Angular 5的更新
With Angular 5, which uses rxjs 5.5.2+ 使用Angular 5,它使用rxjs 5.5.2+
import { filter } from 'rxjs/operators/filter';
import { map } from 'rxjs/operators/map';
These usually come in the stream after the Observable is created. 这些通常在创建Observable后出现在流中。 Like flatMap
in this code snippet: 与此代码段中的flatMap
类似:
Observable.of([1,2,3,4])
.flatMap(arr => Observable.from(arr));
Other such keywords using this syntax: 使用此语法的其他此类关键字:
audit, buffer, catch, combineAll, combineLatest, concat, count, debounce, delay,
distinct, do, every, expand, filter, finally, find , first, groupBy,
ignoreElements, isEmpty, last, let, map, max, merge, mergeMap, min, pluck,
publish, race, reduce, repeat, scan, skip, startWith, switch, switchMap, take,
takeUntil, throttle, timeout, toArray, toPromise, withLatestFrom, zip
FlatMap : flatMap
is alias to mergeMap
so we need to import mergeMap
to use flatMap
. FlatMap : flatMap
是mergeMap
别名,因此我们需要导入mergeMap
以使用flatMap
。
Note for /add
imports : 注意/add
导入 :
We only need to import once in whole project. 我们只需要在整个项目中导入一次。 So its advised to do it at a single place. 因此建议在一个地方进行。 If they are included in multiple files, and one of them is deleted, the build will fail for wrong reasons. 如果它们包含在多个文件中,并且其中一个文件被删除,则构建将因错误原因而失败。
Update for RxJS 6 (April 2018) RxJS 6更新(2018年4月)
It is now perfectly fine to import directly from rxjs
. 现在可以直接从rxjs
导入。 (As can be seen in Angular 6+). (可以在Angular 6+中看到)。 Importing from rxjs/operators
is also fine and it is actually no longer possible to import operators globally (one of major reasons for refactoring rxjs 6
and the new approach using pipe
). 从rxjs/operators
导入也很好,实际上不再可能全局导入运算符(重构rxjs 6
和使用pipe
的新方法的主要原因之一)。 Thanks to this treeshaking can now be used as well. 由于这个树木现在也可以使用。
Sample code from rxjs repo: rxjs repo的示例代码:
import { Observable, Subject, ReplaySubject, from, of, range } from 'rxjs';
import { map, filter, switchMap } from 'rxjs/operators';
range(1, 200)
.pipe(filter(x => x % 2 === 1), map(x => x + x))
.subscribe(x => console.log(x));
Backwards compatibility for rxjs < 6? rxjs的向后兼容性<6?
rxjs team released a compatibility package on npm that is pretty much install & play. rxjs团队在npm上发布了一个兼容包 ,几乎可以安装和播放。 With this all your rxjs 5.x
code should run without any issues. 有了这个,所有你的rxjs 5.x
代码应该运行没有任何问题。 This is especially useful now when most of the dependencies (ie modules for Angular) are not yet updated. 现在,当大多数依赖项(即Angular的模块)尚未更新时,这尤其有用。
One thing I've learnt the hard way is being consistent 我学到的一件事就是坚持不懈
Watch out for mixing: 注意混合:
import { BehaviorSubject } from "rxjs";
with 同
import { BehaviorSubject } from "rxjs/BehaviorSubject";
This will probably work just fine UNTIL you try to pass the object to another class (where you did it the other way) and then this can fail 这可能会正常工作UNTIL你试图将对象传递给另一个类(你以其他方式做到了)然后这可能会失败
(myBehaviorSubject instanceof Observable)
It fails because the prototype chain will be different and it will be false. 它失败了,因为原型链将是不同的,它将是错误的。
I can't pretend to understand exactly what is happening but sometimes I run into this and need to change to the longer format. 我不能假装准确理解发生了什么,但有时我遇到这个并需要更改为更长的格式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.