首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >串口封装在角度工程中的误差

串口封装在角度工程中的误差
EN

Stack Overflow用户
提问于 2021-02-12 03:45:53
回答 1查看 424关注 0票数 0

我试图在我的角度项目中通过串口实现数据读取(使用电子),但是在安装了串口包之后,我得到了“Module”的错误。

以下是我对这个项目的参考。

我所犯的错误

电子服务

代码语言:javascript
复制
import { Injectable } from '@angular/core';
import * as SerialPort from 'serialport';

@Injectable({
  providedIn: 'root'
})

export class ElectronService {
  serialPort: typeof SerialPort;
  constructor() {
    this.serialPort = require('serialport');
  }
}

我的打字文件

代码语言:javascript
复制
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);
  }

}
EN

回答 1

Stack Overflow用户

发布于 2021-03-06 11:36:54

首先,下载ngx-electron 国家预防机制的一揽子方案。这使得IPC变得容易多了。运行:

npm install ngx-electron --save

在您的electron service文件中,尝试执行以下操作:

  • (请注意)来自ngx-electron的这个ngx-electron而不是您在代码中的ElectronService。也许把它的名字改为SerialPortService
代码语言:javascript
复制
import { 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中,您现在可以调用序列化端口方法:

代码语言:javascript
复制
  constructor(private electron: SerialPortService) {}  // <=== Notice I changed the name here.

ngOnInit(): void {
    this.electron.serialPort.list().then((ports: any) => {
      // your code
  }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66166082

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档