javascript - Angular electron mysql create connection 不是一个函数

标签 javascript mysql angular typescript node-mysql

我已经安装了 node js mysql 和 mysql types via

"@types/mysql": "^2.15.4",
"mysql": "^2.15.0"

我将 electron 与 angular2 一起使用,所以在我的组件中我想通过以下方式创建一个连接

import * as mysql from 'mysql'

 @Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
 })

 export class AppComponent implements OnInit {
    connection: any;
    constructor() {
       this.connection = mysql.createConnection({
           host: 'localhost',
           user: 'root',
           password: '5378@Geowan5378',
           database: 'company'
        });

    this.connection.connect((err) => {
        if (err) {
            console.log('error connecting', err);
        }else{
            console.log("connection was a success ");
        }
    });

}   // DI

但是现在出现错误

TypeError: o.createConnection is not a function

这是目前我只在 electron 和 mysql 上学习的唯一组件。我哪里错了?

请注意,错误发生在我调用

this.connection.connect

我不明白这可能是由浏览器中不可用的 Net 库引起的,但在我的例子中,我正在运行 electron . 来启动我的应用程序,所以我没有使用浏览器

或者我如何在不使用服务器端框架的情况下直接将应用程序与 mysql 连接

最佳答案

您必须使用来自 Electron API 的remote 来要求 mysql 而不是使用导入。

  1. 在 index.html 上声明您的远程全局变量

<html>
<head>
...
</head>
<body>

<script>
var remote = require('electron').remote;
</script>
</body>
</html>

  1. 在 app.component.ts 上使用远程

declare var remote :any; // declare remote as any variable

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
 })

 export class AppComponent implements OnInit {
    connection: any;
    constructor() {
      var mysql = remote.require('mysql'); //require mysql with electron remote
       this.connection = mysql.createConnection({
           host: 'localhost',
           user: 'root',
           password: '5378@Geowan5378',
           database: 'company'
        });

    this.connection.connect((err) => {
        if (err) {
            console.log('error connecting', err);
        }else{
            console.log("connection was a success ");
        }
    });

}   // DI

希望对你有所帮助,我建议你用服务改进mysql的加载方法,使其高效地进行查询等。

编辑:或使用我的模块 https://github.com/mochrira/ngx-mysql并学习如何使用它

关于javascript - Angular electron mysql create connection 不是一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50595889/

相关文章:

javascript - 基于 Jquery、JS 中解析的 CSV 文件,使用 JSON 数据填充表

javascript - 如何从 SCORM 云获取completion_status 值?

android - 基于事件应用程序的日期时间实现类似 twitter 的时间线查询

php - 数组比较、while 循环和效率

html - Angular 动画 : div enter behind another div

javascript - 身份验证的架构和思考

javascript - Highcharts 子弹图错误 #13

php - 如何将希伯来语数据库从 latin1_swedish_ci 转换为 utf8?

javascript - 期望验证器返回 Promise 或 Observable

javascript - 如何在 JavaScript 中获取当前 Windows 用户的名称