简体   繁体   English

原型链如何与angular5中的RxJS一起使用?

[英]How chaining of prototypes works with RxJS in angular5?

In an angular 5 project I'm trying to deal with Observables but don't understand how it works when importing separated operators . 在一个有角度的5项目中,我试图处理Observables但不了解导入单独的operators时它如何工作。

Consider chaining a fromPromise with a map : 考虑将fromPromisemap链接fromPromise

import { fromPromise } from 'rxjs/observable/fromPromise';
import { map } from 'rxjs/operator/map';

with fromPromise().map() return the error : fromPromise_1.fromPromise(...).map is not a function fromPromise().map()返回错误: fromPromise_1.fromPromise(...).map is not a function

and

import  'rxjs/add/observable/fromPromise';
import { Observable } from 'rxjs/Observable';
import { map } from 'rxjs/operator/map';

with Observable.fromPromise().map() return the error : Observable_1.Observable.fromPromise(...).map is not a function Observable.fromPromise().map()返回错误: Observable_1.Observable.fromPromise(...).map is not a function

but

import Rx from 'rxjs/Rx';

with Rx.Observable.fromPromise().map() work as expected Rx.Observable.fromPromise().map()一起按预期工作

like 喜欢

import { fromPromise } from 'rxjs/observable/fromPromise';
import { map } from 'rxjs/operator/map';

with map.call(fromPromise(),) map.call(fromPromise(),)

Could someone explains that ? 有人可以解释吗?

Before pipeable operators you have to add an operator to the prototype of Observable to use it. 在使用管道运算符之前,您必须在Observable的原型中添加一个运算符才能使用它。

import  'rxjs/add/observable/fromPromise';

This line adds the fromPromise operator to the prototype for Observable . 此行将fromPromise运算符添加到Observable的原型中。 You can view the source code here . 您可以在此处查看源代码。 That is why the error moved on to map after you added it. 因此,添加错误后,错误会继续显示在map If you also added the one for map then it would likely start working for you. 如果您还为map添加了一个map那么它可能会开始为您工作。

import Rx from 'rxjs/Rx';

This line will import everything which includes monkey patching all of the operators onto the Observable prototype. 该行将导入所有内容,其中包括将所有运算符猴子修补到Observable原型上。 This will likely increase your bundle size so it should be avoided. 这可能会增加您的套装尺寸,因此应避免使用。

If you are using RxJs 5.5+ then you could use pipeable operators instead where you would do: 如果您使用的是RxJs 5.5+,则可以在执行操作的地方使用管道运算符:

import { map } from 'rxjs/operators';

autobots.pipe(map(autobot => transform(autobot));

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

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