RxJS调用from操作符报错Rx.Observable.from is not a function如何解决
问题原因
- RxJS 6及以上版本已经废弃了
Rx.Observable.from的旧写法,所有创建类操作符都需要直接从rxjs包单独导入,不再支持全局Rx对象挂载的调用方式 - Node默认使用CommonJS模块规范,直接使用
import语法需要手动开启ES模块支持,你之前将"type": "module"配置写到package-lock.json属于错误操作,该配置需要放在项目根目录的package.json顶层才会生效 - 你之前执行的
node install rxjs是错误命令,Node本身不是包管理工具,正确的依赖安装命令是npm install rxjs
两种可行解决方案
方案1:使用Node默认CommonJS规范(无需额外配置)
- 先执行正确的安装命令安装依赖:
npm install rxjs
- 代码中使用
require导入from操作符即可正常使用:
const { from } = require('rxjs'); const array = [ '1', 'Max', '2', '3', '4', '5', 'IoT', '6', '7', '8', '9' ]; // 直接调用from创建流 const stream = from(array); // 测试订阅输出 stream.subscribe(val => console.log(val));
直接执行node 你的文件名.js即可正常运行。
方案2:使用ES模块规范(支持import语法)
- 打开项目根目录的
package.json文件(注意不是package-lock.json,后者是自动生成的依赖锁定文件,不要手动修改),在顶层配置中添加"type": "module",参考配置片段:
{ "name": "rxjs-test", "version": "1.0.0", "type": "module", "dependencies": { "rxjs": "^7.8.1" } }
- 代码中直接使用
import导入操作符:
import { from } from 'rxjs'; const array = [ '1', 'Max', '2', '3', '4', '5', 'IoT', '6', '7', '8', '9' ]; const stream = from(array); stream.subscribe(val => console.log(val));
执行node 你的文件名.js即可正常运行。
内容的提问来源于stack exchange,提问作者David
相关产品推荐
相关产品推荐

