使用推荐的操作符导入调用 RxJS 共享时遇到问题 [英] Having trouble calling RxJS share using the recommended operator import

查看:49
本文介绍了使用推荐的操作符导入调用 RxJS 共享时遇到问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试了解导入 rxjs 运算符的最佳实践

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

似乎我应该以这种方式导入 share,但是,以下内容不起作用,因为它说 share 需要 0 个参数.我不太确定如何正确调用 share.

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());

以旧方式进行操作不会造成任何问题.但是我似乎读过这不是导入 https://www.learnrxjs 的首选方式.io/concepts/operator-imports.html

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();

如果我使用推荐的导入方式,我应该如何调用 share ?

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

推荐答案

使用 share 就像任何其他自 RxJS 5.5 以来的pipable"操作符一样:

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

import { share } from 'rxjs/operators';

...

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

有关 pipable 运算符的更多详细信息,请参阅:https:///github.com/ReactiveX/rxjs/blob/master/doc/pipeable-operators.md

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

但是请注意,从 rxjs/operators 导入会导入整个文件 https://github.com/ReactiveX/rxjs/blob/master/src/operators/index.ts.
这意味着如果您自己捆绑应用,它的大小可能会显着增加.

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.

这并不总是必要的.如果您使用的是像 angular-cli 这样的预配置构建系统,它会为您进行路径映射,因此您无需担心它并始终使用 rxjs/operators.您可以阅读有关此内容的更多信息:

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/blob/master/doc/pipeable-operators.md#build-and-treeshaking

这篇关于使用推荐的操作符导入调用 RxJS 共享时遇到问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆