The process of establishing a connection in Angular Electron with MySQL does not involve using the "createConnection

I have successfully set up Node.js, MySQL, and MySQL types.

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

Currently, I am working with Electron and Angular 2. In my component, I attempted to establish a connection using the following code:

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 ");
        }
    });

}   // Dependency Injection

However, I encountered the following error:

TypeError: o.createConnection is not a function

This issue arises when I call

this.connection.connect

It seems like the Net library might not be available in the browser. Nonetheless, I am running electron . to launch my app, so the browser shouldn't be causing this problem.

Is there a way to connect the app directly to MySQL without relying on a server-side framework?

Answer №1

When working with Electron API, it is important to utilize the remote feature to require mysql instead of using import.

  1. To start, declare your remote global variable on the index.html page.

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

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

  1. Next, make use of remote in app.component.ts file.

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 using 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 successful ");
        }
    });

}   // Dependency Injection

It is recommended to enhance the mysql loading process by implementing a service for efficient querying.

Edit: Alternatively, you can explore my module https://github.com/mochrira/ngx-mysql and learn how to integrate it into your project.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Embracing internationalization with Next.js's custom 404 page design

I created a blog posts page with multiple posts listed. Each post has an associated [slug].js file when clicked on. While the default English locale functions correctly, other locales result in a 404 error when attempting to open individual blog posts. A ...

The Angular 4 application fails to refresh automatically after saving changes in the HTML, CSS, or TS files

Software versions: Angular CLI: 1.6.1 Node: 8.2.1 Operating System: linux x64 Additionally, the devDependencies include: "devDependencies": { "@angular/cli": "1.3.2", "@angular/compiler-cli": "4.0.0", "@angular/language-service": "4.2.4", } ...

Leveraging Enjoyhint within nextJS

I am attempting to create a code tour using EnjoyHint, but encountered an error after installing the xbs-enjoyhint library. The error reads: Server Error - ReferenceError: CanvasRenderingContext2D is not defined. This issue is within the jquery.enjoyhint ...

extracting the data from the URL parameter and showing it on the screen

Is there a reason why nothing displays if the name variable is missing from the URL? I've set up code to show a greeting message along with the name value extracted from the URL, but it doesn't work when the name is not present. Any ideas on what ...

Utilizing a Map with Angular's ngFor

Currently, I am working with Ionic 3, which utilizes Angular and TypeScript. My goal is to use ngFor with a Map type in my project. Below is what I have implemented so far: interface IShared_Position { lat: number; lng: number; time: number; ...

What is the best way to eliminate a particular element from an array produced using the .map() function in

I am experiencing an issue with my EventCell.tsx component. When a user clicks on the component, an event is created by adding an element to the components state. Subsequently, a list of Event.tsx components is rendered using the .map() method. The problem ...

What is the best way to extract clean text from HTML using JavaScript?

I am struggling with the code below in my HTML file: function hideContent(){ // Need help with this part! } <input type="button" onclick="hideContent()" value="Hide Content"/> <p id='txt'> <span class="A">I am</span> ...

Alter the views of a bootstrap date picker in real-time

Is there a way to dynamically change the date picker's view based on different button selections? For example, I have buttons for month, year, and day. Here is what I am trying to achieve: When the month button is selected: I want the date picker ...

Tips for isolating all the Javascript loaded via ajax or jquery.load within a specific child scope instead of a global scope

I am currently working on a solution to embed a third-party page into my site using ajax/jquery.load() to avoid using iframes (CORS requirements are already handled by the third party). My dilemma lies in the fact that the main host site loads jquery 1.x ...

"Turn off sweep gesture on Surface tablet when using Chrome after pinching to zoom

In the process of developing my app, I encountered the need to disable zooming and scrolling, which I addressed using the viewport meta tag: <meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-sc ...

When an array is pushed into another array in JavaScript, it reverts back to its original values

My implementation of recursion involves trying different pieces in a matrix: function solve(matrix, pieces) { // Get next -1 let nextEmpty = getNextEmtpy(matrix); if (!nextEmpty) { console.log(matrix) solutions.push(matrix); ...

How can I conceal the contents of a webpage until the entire page has finished loading before revealing them?

Is there a way to delay displaying my login template until all elements are fully loaded? Currently, when I visit the site, the template appears first followed by fonts and other components. I want to ensure that nothing is shown to the user until the enti ...

Automating Jquery clicks with a built-in delay feature - possible solution

My attempt to create a jQuery script that clicks all elements from a specific class with a delay using setTimeout when a checkbox is checked and 'automatic send' button is clicked is not working as expected. Here is a snippet of my HTML/PHP code: ...

Integrate fresh data into an array using Vue

Exploring VUE for the first time, I am working on a project where I need to update an array by passing an object. The scenario involves two buttons named BUTTON 1 and BUTTON 2. Clicking on BUTTON 1 sets an object in the list[] using this.$set. However, whe ...

Tips for effectively enabling Node.js to execute its asynchronous events within my infinite while loop

Every time I execute my 'save_to_db' function at location B, it ends up failing. Below is the snippet of code that highlights the issue... //location A var i = 0; while(true) { i++; if(i == 100) { //location B save_to_d ...

Recursive function to filter through an array and search for parent elements

I have an array structured like this: [ {"id":"one","name":"school", "selected": false, "children":[ {"id":"1","name":"school", "selected": false}, {"id":"2","name":"student", "selected": true}, {"id":"3","name":"teacher", "selected" ...

Encountering a surprising token error while running a node.js application with a classic example

I downloaded node.js from its official website and followed the instructions provided here. I attempted to run the example code snippet from the "JavaScript - The Good Parts" textbook: var myObject = { value: 0; increment: function (inc) { this.value ...

Obtaining the "match" object within a Custom Filter Selector on jQuery version 1.8

Here's a helpful resource on Creating a Custom Filter Selector with jQuery for your reference. A Quick Overview: If you're unfamiliar with jQuery's Custom Filter Selectors, they allow you to extend jQuery’s selector expressions by addi ...

Issue with autocomplete feature malfunctioning on both php and javascript

I'm currently working on a simple auto-complete script using Javascript and PHP, but I'm running into some issues. Any help would be greatly appreciated! Here's the HTML code I have: <!doctype html> <html lang="en"> <head> ...

"Addressing the challenge of deploying Typescript GraphQL in a live production

For the past week, I've been struggling to research and deploy my server into production. My setup includes Typescript, Nexus GraphQL, Prisma with docker-compose. During development, everything runs smoothly using ts-node-dev. However, when attempting ...