Angular 2 , Nodejs, and postgresql

Viewed 1183

So I want to display some data on front-end from the database.

My app.js file has included:

app.use('/database', databaseRoutes);

my database.js file is the next.

const { Pool, Client } = require('pg')
const connectionString = "postgres://dbuser:Storerage@localhost/mainstorage"

const client = new Client({
  connectionString: connectionString,
})
client.connect()

client.query('SELECT * FROM files limit 10', (err, res) => {
  console.log(err, res)
  client.on("row", function (row, result) {
    result.addRow(row);
});

});
module.exports = client;

How can I display this postgresql query result in document.component.html.

Can somebody link me any kind of help, or write an introduction ?

I think I need create a document.service file but I don't know how to handle that. I have read about JSON.stringify, but didn't find any cool tutorial.

Thanks for help.

2 Answers

I think you have trouble understanding the concept of an API. First of all you should retrieve the query results via res.send(results) (or res.end, whichever suits you). That will retrieve the data in a JSON format which you can easily parse using either modules like lodash or just simply by accessing them like any object (using either object.attr or object['attr']). You should create endpoints to which you'll send requests from your Angular front-end and those endpoints will retrieve results in JSON or whichever format. I can't go through all the steps here, but you should check out some tutorials on REST APIs for starters.

You need a Node.js server, like Express, or just the internal server of NodeJS is OK. I suggest Express. Then you put your code in a route's callback function, after you've fetched data form the database, use res.send() or res.json() to send result to the client. Why don't you just have a look of Express at expressjs.com, it's very simple. Or I should suggest you using some frameworks on a higher level to organize your code. I wrote a framework, Cool-Node, it base on Express and Socket.io and some other strong modules, Also, I published an ORM module, Modelar, its easier to handle data with an ORM tool. Cool-Node uses Modelar as well, it currently supports MySQL, PostgreSQL and SQLite, with a powerful Query Constructor, it provides an API that gives you the ability to handle data in an object-oriented way.

Related