如何正确引用rxjs库进行声明或要求?

时间:2018-11-13 02:12:37

标签: node.js rxjs require

使用nodejs和打字稿检查another answer to a different question时,出现此异常:

  

TypeError:interval $ .zip不是函数

我的代码(rxjs2.ts):

{
    var Rx = require('rxjs');

    const interval$ = Rx.interval(1000);
    const items$ = Rx.from([1,2,3]);

    const itemsOverTime$ = interval$.zip(items$).repeat();

    itemsOverTime$.subscribe(([time, val]) => {
    console.log(val);
    // 1
    // 2
    // 3
    // 1
    // 2
    // 3
    });
}

从VSCode控制台运行此文件,例如:node rxjs2.ts

我的package-lock.json

{
  "requires": true,
  "lockfileVersion": 1,
  "dependencies": {
    "@types/node": {
      "version": "10.12.2",
      "resolved": "https://registry.npmjs.org/@types/node/-/node-10.12.2.tgz",
      "integrity": "sha512-53ElVDSnZeFUUFIYzI8WLQ25IhWzb6vbddNp8UHlXQyU0ET2RhV5zg0NfubzU7iNMh5bBXb0htCzfvrSVNgzaQ=="
    },
    "rxjs": {
      "version": "6.3.3",
      "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-6.3.3.tgz",
      "integrity": "sha512-JTWmoY9tWCs7zvIk/CvRjhjGaOd+OVBM987mxFo+OW66cGpdKjZcpmc74ES1sB//7Kl/PAe8+wEakuhG4pcgOw==",
      "requires": {
        "tslib": "1.9.3"
      }
    },
    "tslib": {
      "version": "1.9.3",
      "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.9.3.tgz",
      "integrity": "sha512-4krF8scpejhaOgqzBEcGM7yDIEfi0/8+8zDRZhNZZ2kjmHJ4hv3zCbQWxoJGz1iw5U0Jl0nma13xzHXcncMavQ=="
    }
  }
}

1 个答案:

答案 0 :(得分:0)

您的导入错误,而且访问方式也错误。

这应该有效:

StackBlitz

import { interval, from, zip } from 'rxjs';
import { repeat } from 'rxjs/operators';

const interval$ = interval(1000);
const items$ = from([1, 2, 3]);

const itemsOverTime$ = zip(interval$, items$).pipe(repeat());

itemsOverTime$.subscribe(([time, val]) => {
  console.log(val);
  // 1
  // 2
  // 3
  // 1
  // 2
  // 3
});

更新: 这是CommonJS导入的解决方案。如果您希望使用旧的语法和导入,则需要使用npm安装rxjs-compat。请参阅此文档Rxjs Doc

Stackblitz

const Rx = require('rxjs/Rx');
const repeat = require('rxjs/operator/repeat');


const interval$ = Rx.Observable.interval(1000);
const items$ = Rx.Observable.from([1, 2, 3]);

const itemsOverTime$ = Rx.Observable.zip(interval$, items$).repeat();

itemsOverTime$.subscribe(([time, val]) => {
   console.log(val);
   // 1
   // 2
   // 3
   // 1
   // 2
   // 3
});

更新2:

对于CommonJS和新版本的RxJ,您需要这样做:

StackBlitz

const Rx = require('rxjs');
const RxOp = require('rxjs/operators');

const interval$ = Rx.interval(1000);
const items$ = Rx.from([1, 2, 3]);

const itemsOverTime$ = Rx.zip(interval$, items$).pipe(RxOp.repeat());

itemsOverTime$.subscribe(([time, val]) => {
  console.log(val);
  // 1
  // 2
  // 3
  // 1
  // 2
  // 3
});