Having trouble calling RxJS share using the recommended operator import

落花浮王杯 提交于 2019-12-24 02:56:12

问题


I'm trying to understand the best practice for importing rxjs operators

It seems like I should import share this way, but, the following doesn't work because it says share expects 0 arguments. I'm not quite sure how to call share correctly.

import { share } from 'rxjs/operators';

...

public currentUser: Observable<User> = share(this.currentUser$.asObservable());

Doing it the old way causes no problems. However I seemed to have read that's not the preferred way to import https://www.learnrxjs.io/concepts/operator-imports.html

import 'rxjs/add/operator/share';

...

public currentUser: Observable<User> = this.currentUser$.asObservable().share();

How should I call share if I'm using the recommended way of importing?


回答1:


Using share is like any other "pipable" operator since RxJS 5.5:

import { share } from 'rxjs/operators';

...

this.currentUser$.pipe(share());

For more details about pipable operators see: https://github.com/ReactiveX/rxjs/blob/master/doc/pipeable-operators.md

However be aware that importing from rxjs/operators imports this entire file https://github.com/ReactiveX/rxjs/blob/master/src/operators/index.ts.
This means that if you bundle your app yourself it might grow in size significantly.

So you might want to import each operator from it's own file like:

import { share } from 'rxjs/internal/operators/share';

... and then use it the same way.

This isn't always necessary. If you're using a preconfigured build system like angular-cli it does path mappings for you so you don't need to worry about it and always use rxjs/operators. You can read more about this:

  • https://github.com/ReactiveX/rxjs/issues/3018

  • https://github.com/ReactiveX/rxjs/blob/master/doc/pipeable-operators.md#build-and-treeshaking




回答2:


In RxJs 5.5 onwards, RxJs introduce Pipeable (or lettable) operators. Read in details here: https://github.com/ReactiveX/rxjs/blob/master/doc/pipeable-operators.md

In short, using the below way is good in Rxjs 5.5 especially if you are using typescript.

import { share } from 'rxjs/operators';



回答3:


Your first way of importing import { share } from 'rxjs/operators' is wrong because that is just importing the share operator class not the method operator.

In the second example import 'rxjs/add/operator/share' this is correct because it is saying I would like to add the share operator to my observable.

There's also letable operators in rxjs 5.5 like Chybie says but for your use case number 2 is correct.



来源:https://stackoverflow.com/questions/48250322/having-trouble-calling-rxjs-share-using-the-recommended-operator-import

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!