How to correctly import operators from the `rxjs` package

There are static and instance operators in RxJS:

static
   of
   interval

instance
   map
   first

You may want to use these on the Observable global object or observable instance like this:

Observable.of()
observableInstance.map()

For that you need to import modules from the add package:

import 'rxjs/add/observable/of'
import 'rxjs/add/operator/map'

When you import the module it essentially patches Observable class or Observable prototype by adding method corresponding to the operators.

But you can also import these operators directly and don’t patch Observable or observableInstance:

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

of()
map.call(observableInstance)

With the introduction of lettable operators in [email protected] you should now take advantage of the built-in pipe method:

import { of } from 'rxjs/observable/of';
import { map } from 'rxjs/operators/map';

of().pipe(map(), ...)

Read more in RxJS: Understanding Lettable Operators

Leave a Comment