角度电子mysql创建conncetion不是一个函数

时间:2018-05-30 03:20:06

标签: javascript mysql angular typescript node-mysql

我已经通过

安装了节点js mysql和mysql类型
"@types/mysql": "^2.15.4",
"mysql": "^2.15.0"

我使用带有angular2的电子所以在我的组件中我想通过

创建一个conncection
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

这是迄今为止只学习电子和mysql的唯一组件。我哪里错了?

请注意,当我致电

时会发生错误
this.connection.connect

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

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

1 个答案:

答案 0 :(得分:0)

您必须使用Electron API中的远程来要求使用mysql而不是使用导入。

  1. 在index.html上声明您的远程全局变量
  2. 
    
    <html>
    <head>
    ...
    </head>
    <body>
    
    <script>
    var remote = require('electron').remote;
    </script>
    </body>
    </html>
    &#13;
    &#13;
    &#13;

    1. 在app.component.ts
    2. 上使用遥控器

      &#13;
      &#13;
      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
      &#13;
      &#13;
      &#13;

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

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