In my angular 2 app I have a service that uses the Observable
class from the rxjs
library.
import { Observable } from 'rxjs';
At the moment I am just using Observable
so that I can use the toPromise()
function.
I read in another StackOverflow question somewhere that importing in this way and also importing from rxjs/Rx
will import a whole lot of unnecessary stuff from the rxjs
library that will increase the page load times and/or the code base.
My question is, what is the best way to import Observable
so I can use the toPromise()
function without having to import everything else?
This question is related to
angular
typescript
rxjs
angular2-observables
Update for RxJS 6 (April 2018)
It is now perfectly fine to import directly from rxjs
. (As can be seen in Angular 6+). Importing from rxjs/operators
is also fine and it is actually no longer possible to import operators globally (one of major reasons for refactoring rxjs 6
and the new approach using pipe
). Thanks to this treeshaking can now be used as well.
Sample code from rxjs repo:
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));
Backwards compatibility for rxjs < 6?
rxjs team released a compatibility package on npm that is pretty much install & play. With this all your rxjs 5.x
code should run without any issues. This is especially useful now when most of the dependencies (i.e. modules for Angular) are not yet updated.
One thing I've learnt the hard way is being consistent
Watch out for mixing:
import { BehaviorSubject } from "rxjs";
with
import { BehaviorSubject } from "rxjs/BehaviorSubject";
This will probably work just fine UNTIL you try to pass the object to another class (where you did it the other way) and then this can fail
(myBehaviorSubject instanceof Observable)
It fails because the prototype chain will be different and it will be false.
I can't pretend to understand exactly what is happening but sometimes I run into this and need to change to the longer format.
Source: Stackoverflow.com