在引用最新的rxjs时获取rxjs错误

getting rxjs errors when referencing latest rxjs

本文关键字:rxjs 错误 获取 引用 最新      更新时间:2024-06-23

我正在使用本教程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

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

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

更新2018/12:

RxJS v6.x引入了一种新的、更具"功能性"的API。有关更多信息,请参阅5>6迁移指南。原始示例代码仍然有效,但您必须导入of运算符,如下所示:

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

原始RxJS 5答案:

没错。RxJS 5被重写以提高性能,同时也符合ES7 Observable规范。查看Github上的RxJS 4->5迁移页面。

下面是一个工作示例:

// 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的可观测性混合在一起。

因此,我通过更新所有调用以使用最新的rxjs来解决问题。