I would like to move AngularJS project to Angular Universal.
In AngularJS I had $http requests using PHP. For example I had the following code in Services:
this.getNewItems = function () {
var request = $http({
method: "GET",
url: "PHP/newitems.php",
params: {
number: "3"
}
});
return ( request.then(handleSuccess, handleError) );
};
Now as I use Node.js with Universal I would like to use Http request with Node.js.
So in component's constructor I should use the construction:
export class HomeComponent {
mydata: any = {};
constructor(http:Http) {
http.get('??????').subscribe(data => {
this.mydata = data;
});
}
}
If I would use JSON-file then I have found many examples like this:
http.get('test.json').subscribe(data => {
this.mydata = data;
});
However all my data is in existing MySQL database. So I would like to understand how I can reach my data in database.
I have already installed npm MySql component by
npm install mysql
I have found that a connection with Node.js is setting by:
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'host',
user : 'user',
password : 'password',
database : 'dbname'
});
connection.connect(function(err) {
// in case of error
if(err){
console.log(err.code);
console.log(err.fatal);
}
});
If I use this connection code in Component's constructor then some errors return, like
ERROR in ./~/mysql/lib/Connection.js
Module not found: Error: Can't resolve 'net'
So how I can integrate the connection code with http.get() request?
Thanks a lot.
Addition: now I came to this (it concerns my starter project for Angular Universal https://github.com/angular/universal-starter):
In Component I use the following code:
export class HomeComponent {
mydata:any = []; constructor(public model: ModelService) { this.model.get('/api/getmydata') .subscribe(data => { this.mydata = data; console.log("My data: " + this.mydata); }); } }
2.In backend/api.ts I've added:
router.route('/getmydata')
.get(function(req, res) {
setTimeout(function() {
res.json(Mydata);
}, 0);
}
If Mydata is a JSON then all works properly and I receive the data. However I would like to connect to MySQL database. So I add a connection code:
router.route('/getmydata')
.get(function(req, res) {
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'root',
database : 'mydatabase',
port: '8889'
});
connection.connect(function(err) {
if (err) {
console.log("Error connecting to DB: " + err);
throw err;
}
});
...
}
Here I receive errors:
TypeError: Cannot read property 'on' of undefined
at Protocol._enqueue (/Applications/MAMP/htdocs/Angular2/myproject/node_modules/mysql/lib/protocol/Protocol.js:152:5)
...
Then
Error connecting to DB: Error: Connection lost: The server closed the connection.
If anyone knows how to fix the connection to database I would highly appreciate the advice.