Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
853 views
in Technique[技术] by (71.8m points)

angular - How to correctly import operators from the `rxjs` package

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...