10

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

我正在引用 npm 包中的最新rx.umd.js版本,rxjs@5.0.0-beta.6"<script src="node_modules/rxjs/bundles/rx.umd.js"></script> 是我要运行的代码:

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()受支持?

4

2 回答 2

10

2018/12 更新:

RxJS v6.x 引入了一个新的、更具“功能性”的 API。查看5>6 迁移指南以获取更多信息。原始示例代码仍然有效,但您必须of像这样导入运算符:

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

原始 RxJS 5 答案:

这是正确的。RxJS 5 被重写以提高性能并符合 ES7Observable规范。查看 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 本身很容易过渡到。

于 2016-04-14T03:59:43.483 回答
0

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

old.dispose is not a function

就我而言,问题在于我将一些旧的 rxjs 与来自较新版本的 rxjs 的 observable 混合在一起。

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

于 2019-07-19T12:17:54.013 回答