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
240 views
in Technique[技术] by (71.8m points)

javascript - How to import `Observable` from `Rx` (not angular)

I'm using SystemJS to load my es2015 project into the browser.

This is what I did

import {Observable} from 'rxjs/Rx';

const button = document.querySelector('button');
const start$ = Observable.fromEvent(button, 'click');

In this case Observable is undefined. So I tried

import Observable from 'rxjs/Observable';

In which case Observable is an object but Observable.fromEvent is undefined (it seems to be an empty object)

Finally I did

import Rx from 'rxjs/Rx' // Rx.Observable

which did work. Any ideas why the other two didn't work? I have seen code in which they used these. What would be the preferred way to import Observable?

UPDATE: As stated below its all described in the README. However if I do that

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/fromEvent';

const start$ = Observable.fromEvent(startButton, 'click');

I get Observable is undefined. And if I do

import Observable from 'rxjs/Observable';

the Observable is an empty object again. The fromEvent is not added.

I'm using RxJs 5.1.1 and here is my index.html/systemjs part:

 <script src="./node_modules/systemjs/dist/system.js"></script>
  <script>
      SystemJS.config({
          baseURL: 'node_modules',
          packages: {
              '.': {
                  defaultJSExtensions: 'js'
              }
          },
          map: {
              'plugin-babel': 'systemjs-plugin-babel/plugin-babel.js',
              'systemjs-babel-build': 'systemjs-plugin-babel/systemjs-babel-browser.js'
          },
          transpiler: 'plugin-babel'
      });

      SystemJS.import('/js/main.js');
  </script>
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

As it notes in the README, you can use import { Observable } from 'rxjs/Observable';:

To import only what you need by patching (this is useful for size-sensitive bundling)

This gives you a very minimal Observable, to which you need to explicitly add any extra functionality you plan to use; in your case, follow it with:

import 'rxjs/add/observable/fromEvent';

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

...