Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to correctly import operators from the `rxjs` package

Tags:

angular

rxjs

I am confused how to import those operators. Some I can import with import 'rxjs/add/operator/do'; and some I can not. For ex, this does not work: import 'rxjs/add/operator/map'; (I checked in rxjs/add/operator, map exists there).

Essentially what I am trying to do is to reproduce this in Angular4:

var requestStream = Rx.Observable.just('https://api.github.com/users');

var responseStream = requestStream
  .flatMap(function(requestUrl) {
    return Rx.Observable.fromPromise(jQuery.getJSON(requestUrl));
  });

responseStream.subscribe(function(response) {
  // render `response` to the DOM however you wish
});

I also want to know how to deal with just operator, since I can not see it in rxjs/add/operator...

Thanks for any help

like image 429
Julius Dzidzevičius Avatar asked Aug 03 '17 12:08

Julius Dzidzevičius


2 Answers

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

like image 183
Max Koretskyi Avatar answered Dec 20 '22 16:12

Max Koretskyi


Lower version of rxjs has got folder

node_modules\rxjs\operator

Higher version of rxjs has got folder

node_modules\rxjs\operators

Please make sure the typescript file location is exists for map and other operators exists within.

If problem still persist please delete rxjs folder from node_modules and run the command

npm  install --save 

usually this causes due to lowering the package version from higher version of rxjs.

like image 44
Mark Macneil Bikeio Avatar answered Dec 20 '22 16:12

Mark Macneil Bikeio