0

Hi there I’m having like an existencial crisis about this.

Can anyone give my an example of how to connect my Angular (I’m using angular 6) frontend with a MySQL database (not a NoSQL example please, there are plenty of those), using node/express backend?

I’ve been reading over the weekend, searching google, stack, youtube, etc, and there are many examples of something just about but not quite enough for me to understand. What I cannot figure is how do I push a button in my frontend, do a call do my DB and make it appear in my website (basically all CRUD operations).

I need hard code. I don’t have any code of mine cause I can’t even imagine how to make in my app.js connect with the button in my angular component to make a crud operation to the mysql DB. I’m REALLY confused.

Assume I'm using phpmyadmin for MySQL and there is a Database named users, 1 column with user_name and one value of Aquiles. With that I would like to read, update, delete.

Links for others posts (I searched them pretty much all of them though), videos, tutorials, are all welcome.

Thanks for your time, Regards.

sebaLinares
  • 485
  • 5
  • 17

1 Answers1

6

I did it

To respond to my own question and if there is any soul in despair because of this, here it is.

1. Create a db and table in phpmyAdmin or your desired database.

CREATE TABLE IF NOT EXISTS 'tasks' (

  'id' int(11) NOT NULL,
  'task' varchar(200) NOT NULL,
  'status' tinyint(1) NOT NULL DEFAULT '1',
  'created_at' datetime NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;



ALTER TABLE 'tasks' ADD PRIMARY KEY ('id');
ALTER TABLE 'tasks' MODIFY 'id' int(11) NOT NULL AUTO_INCREMENT;

INSERT INTO 'tasks' ('id', 'task', 'status', 'created_at') VALUES
(1, 'Find bugs', 1, '2016-04-10 23:50:40'),
(2, 'Review code', 1, '2016-04-10 23:50:40'),
(3, 'Fix bugs', 1, '2016-04-10 23:50:40'),
(4, 'Refactor Code', 1, '2016-04-10 23:50:40'),
(5, 'Push to prod', 1, '2016-04-10 23:50:50');

I took this from reading this post Creating a RESTful API with Express js, Node js/MySQl - Arjun

2. Backend: Server + API endpoint

const express = require('express');
    const mysql = require('mysql');
    const bodyParser = require('body-parser');
    const app = express();

    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({
        extended: true
    }));

    // Connect my db
    var connection = mysql.createConnection({
      host     : 'localhost',
      user     : 'root',
      password : '',
      database : 'dbName'
    });

    connection.connect(function(err) {
        if (err) {
          console.error('error connecting: ' + err.stack);
          return;
        }

        console.log('connected as id ' + connection.threadId);
    });

    app.get('/', function (req, res) {
    res.send('Hello World!');
    });

    // Port that will be listened
    app.listen(3000, function () {
      console.log('Example app listening on port 3000!');
    });

    // the query
    querie = 'SELECT * FROM tasks';

**THIS IS THE API ENDPOINT FOR THE GET REQUESTS**

    app.get('/todos', function (req, res) {
        connection.query(querie, function (error, results, fields) {
            if (error) throw error;
            return res.send({ error: false, data: results, message: 'Todos list.' });
        });
    });

3. Angular

The app.component.html file

<button
  (click)="getData()">GET Profile
</button>

4. The app.component.ts file

import { Component } from '@angular/core';
import { HttpClient } from "@angular/common/http";

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  constructor (private httpClient:HttpClient){ }

  getData(){
    this.httpClient.get('/api/todos')
      .subscribe(
          (data:any[]) => {
            console.log(data);
          }
        )
  }
}

Finally

Now you need to start your angular project in one terminal windows and the server in another. One will be in port 4200 (angular) and the server will be in localhost:3000 like we configured it in our app.js.

The problem is that when you make a get request from your frontend through port :4200 you result in an error. It says that your requests is going trough http://localhost:4200/localhost:3000 or something very similar to that (it’s late and I didn’t document the exact error, sorry). So after some research I encountered with this post https://medium.freecodecamp.org/the-best-ways-to-connect-to-the-server-using-angular-cli-b0c6b699716c and used the “proxy approach”.

Voilá, in my javascript console there is an array with everything that my database had inside.

Read this articles to have a clearer view of everything. It’s a pretty poor explanation(for advanced ones).

  1. the-best-ways-to-connect-to-the-server-using-angular-cli
  2. same-port-4200-for-both-production-an
  3. stories-proxy
  4. proxy-for-api-calls-for-your-angular-cli-app

Regards.

sebaLinares
  • 485
  • 5
  • 17