引用最新的 rxjs 时出现 rxjs 错误

getting rxjs errors when referencing latest rxjs

我正在使用本教程 https://egghead.io/lessons/rxjs-creating-an-observable,它引用了 2.5.2 rxjs 版本。

我引用了来自 rxjs@5.0.0-beta.6" npm 包 <script src="node_modules/rxjs/bundles/rx.umd.js"></script> 的最新 rx.umd.js 这是我正在尝试的代码 运行:

console.clear();

var source = Rx.Observable.create(function(observer){
    setTimeout(function() {
        console.log('timeout hit');
        observer.onNext(42);
        observer.onCompleted();
    }, 1000);

    console.log('started');
});

var sub = source.subscribe(function(x) {
    console.log('next ' + x);
}, function(err) {
    console.error(err);
}, function() {
    console.info('done');
});

setTimeout(function() {
    sub.dispose()
}, 500);

这是我得到的控制台输出。

Console was cleared
script.js:10 started
script.js:22 Uncaught TypeError: sub.dispose is not a function
script.js:5 timeout hit
script.js:6 Uncaught TypeError: observer.onNext is not a function

笨蛋:https://plnkr.co/edit/w1ZJL64b8rnA92PVuEDF?p=catalogue

rxjs 5 api 是否与 rxjs 2.5 有很大不同并且 observer.onNext(42);sub.dispose() 不再受支持?

2018/12 更新:

RxJS v6.x 引入了一个新的,更多 "functional" API。查看 5>6 migration guide 了解更多信息。原始示例代码仍然有效,但您必须像这样导入 of 运算符:

// ESM
import { of } from 'rxjs'
// CJS
const { of } = require('rxjs');

原 RxJS 5 答案:

没错。 RxJS 5 被重写以提高性能并符合 ES7 Observable 规范。查看 Github 上的 RxJS 4->5 migration page

这是一个工作示例:

// Create new observable
const one = Observable.of(1,2,3);

// Subscribe to it
const oneSubscription = one.subscribe({
    next: x => console.log(x),
    error: e => console.error(e),
    complete: () => console.log('complete')
});

// "Dispose"/unsubscribe from it
oneSubscription.unsubscribe();

很多方法重命名了,但是API本身很容易过渡到。

不确定这是否可以帮助那里的人,但我最终遇到了类似的错误:

old.dispose is not a function

在我的例子中,问题是我将一些旧的 rxjs 与来自较新版本的 rxjs 的 observables 混合在一起。

所以我通过更新所有调用以使用最新的 rxjs 解决了问题。