3

I would like to use RxJS without Angular or Webpack. I just included RxJS 7 from a CDN. This is what I tried:

const { Observable } = rxjs;

const clicks = Observable.fromEvent(document, 'click');

clicks.subscribe(ev => console.log(ev))

I get this error:

Uncaught TypeError: Observable.fromEvent is not a function

My html code looks like this:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/7.3.0/rxjs.umd.js" integrity="sha512-1Jz97rlEAHdMk6x3UWesQaEOhSZ3iG82PkqNr3N4bj/hqKaVQDPTeHW0//vU1ucY+pB5sZr5uNz1aO2qO5XkMg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    <script src="demo.js"></script>
</head>
<body>
    demo
</body>
</html>

There is a similar question, but that is different, because it uses Angular, but I don't use any build system, just include it from a CDN.

What do I wrong? How to use Observable.fromEvent?

Iter Ator
  • 8,226
  • 20
  • 73
  • 164

3 Answers3

4

Starting from RxJS@6, fromEvent function is not a part of the Observable class, and instead, you need to use it directly from rxjs.

Try the following:

const { Observable, fromEvent } = rxjs;

const clicks = fromEvent(document, 'click');

clicks.subscribe(ev => console.log(ev));
Amer
  • 6,162
  • 2
  • 8
  • 34
1

Import fromEvent and use that directly instead of importing Observable.

import { fromEvent } from 'rxjs';

Edit: my apologies as I forgot you are in the browser side. Using the CDN will declare the global variable rxjs so you should use rxjs.fromEvent.

Joshua McCarthy
  • 1,739
  • 1
  • 9
  • 6
  • I use it in plain html+js. There is no import statement: `Uncaught SyntaxError: Cannot use import statement outside a module` – Iter Ator Sep 03 '21 at 14:47
-1

Use rxjs version 5.x or update your imports

Alfredo Tavares
  • 147
  • 1
  • 4