我试图在我的角度项目中通过串口实现数据读取(使用电子),但是在安装了串口包之后,我得到了“Module”的错误。
以下是我对这个项目的参考。
电子服务
import { Injectable } from '@angular/core';
import * as SerialPort from 'serialport';
@Injectable({
providedIn: 'root'
})
export class ElectronService {
serialPort: typeof SerialPort;
constructor() {
this.serialPort = require('serialport');
}
}我的打字文件
import { Component } from '@angular/core';
import * as SerialPort from 'serialport';
import { ElectronService } from './electron.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
title = 'serial-port';
serialPort: typeof SerialPort;
constructor(private electron: ElectronService) {
}
ngOnInit(): void {
this.electron.serialPort.list().then((ports: any) => {
{
console.log("true")
}
}).catch((err: any) => {
{
console.log("Error" + err)
}
});
console.log(this.serialPort);
}
}发布于 2021-03-06 11:36:54
首先,下载ngx-electron 国家预防机制的一揽子方案。这使得IPC变得容易多了。运行:
npm install ngx-electron --save
在您的electron service文件中,尝试执行以下操作:
ngx-electron的这个ngx-electron是而不是您在代码中的ElectronService。也许把它的名字改为SerialPortServiceimport { Injectable } from '@angular/core';
import { ElectronService } from "ngx-electron"; // <=== Added this line
// import * as SerialPort from 'serialport'; <==== Removed this line
@Injectable({
providedIn: 'root'
})
export class SerialPortService{
public SerialPort: any;
constructor(private electron: ElectronService) {
this.SerialPort = electron.remote.require("serialport"); // <=== Crucial line here
}
}然后,在您的component.ts中,您现在可以调用序列化端口方法:
constructor(private electron: SerialPortService) {} // <=== Notice I changed the name here.
ngOnInit(): void {
this.electron.serialPort.list().then((ports: any) => {
// your code
}https://stackoverflow.com/questions/66166082
复制相似问题