Whats the difference between importing RxJS functions and methods using only a string and importing using a named import. For example:
Using the 'add' string:
import 'rxjs/add/operator/map'
Using a named import
import { merge } from 'rxjs/observable/merge'
An individual method only works one way but I can't work out how to tell which way a particular method needs to be imported. Is there a way to determine which method to use, and what's the difference?
The first import will patch the Observable prototype with the map method so it will be available on all instances of this type.
The second one is importing just a function that can be called with some arguments and will return an Observable.
Patching the prototype does not work well with things like tree shaking so in the latest versions of RxJs the pipe method was added and all the imports are named.
Example from RxJs readme:
import { Observable, Subject, ReplaySubject, from, of, range } from 'rxjs';
import { map, filter, switchMap } from 'rxjs/operators';
range(1, 200)
.pipe(filter(x => x % 2 === 1), map(x => x + x))
.subscribe(x => console.log(x));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With