我已经安装了 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 而不是使用导入。
- 在 index.html 上声明您的远程全局变量
<html>
<head>
...
</head>
<body>
<script>
var remote = require('electron').remote;
</script>
</body>
</html>
- 在 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/