简体   繁体   中英

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 .

Consider chaining a fromPromise with a map :

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

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

but

import Rx from 'rxjs/Rx';

with Rx.Observable.fromPromise().map() work as expected

like

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

with map.call(fromPromise(),)

Could someone explains that ?

Before pipeable operators you have to add an operator to the prototype of Observable to use it.

import  'rxjs/add/observable/fromPromise';

This line adds the fromPromise operator to the prototype for Observable . You can view the source code here . That is why the error moved on to map after you added it. If you also added the one for map then it would likely start working for you.

import Rx from 'rxjs/Rx';

This line will import everything which includes monkey patching all of the operators onto the Observable prototype. 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:

import { map } from 'rxjs/operators';

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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