How to interface JSON data and display table - mysql

So I am trying to display a list of devices from the database into an angular material table. I've written the REST api for it which is something like this:
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const mysql = require('mysql');
//parse application/json
app.use(bodyParser.json());
//create database connection
const conn = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'project'
});
//connect to database
conn.connect((err) =>{
if(err) throw err;
console.log('Mysql connected....');
});
//server listening
app.listen(3000,() =>{
console.log('Server started on port 3000');
});
//show login page
app.use(express.static(__dirname+'/dashboard'))
app.get('/',(req,res) => {
res.send('Use /api/devices');
});
//show all devices
app.get('/api/devices',(req,res) => {
let sql = "SELECT * FROM tempstatus";
let query = conn.query(sql, (err, results) => {
if(err) throw err;
res.send(JSON.stringify({'status': 200, 'error': null, 'response': results}));
});
});
And now I have written a controller as follows:
var myApp = angular.module('myApp', [require('angular-material-data-table')]);
myApp.controller('DeviceController', function($scope, $http){
console.log('DeviceController loaded')
$scope.getDevices = function(){
var device = null;
$http.get('/api/devices').success(function(response) {
device = response;
});
}
}
I'm rather new to Angular and nodejs and I don't really know how what else I must do and how to display the data I get in an angular material table. Can you please help me out?
This is the JSON data I'm getting from the API:
"status":200,"error":null,"response": {"serialnum":"0","time":"2020-02-11T12:36:27.000Z","type":"","temparature":"","date":"2020-02-10T18:30:00.000Z","status":"not active","comments":""}
And this is the angular.module.ts file. As I said, I'm new to angular and I don't know how to write my code. So far I've only done this and the controller in angular:
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { HttpClientModule } from '#angular/common/http';
#NgModule({
declarations: [
AppComponent,
],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }

Related

Display data retrieved from mysql in piechart

I need some help in creating a pie chart in react for the data retrieved from mysql database.
App.js code :
import React , { PureComponent } from 'react';
import {useState , useEffect } from 'react';
import './App.css';
import { PieChart , Pie , Tooltip } from "recharts";
function App() {
const [category, setCategory] = useState([]);
useEffect(()=>{
const getDbData = async ()=>{
const getA = await fetch('http://localhost:3001/posts/');
const getData = await getA.json();
setCategory(getData);
console.log(getData);
// console.log(data);
}
getDbData();
},[])
return (
<div className="App">
<h1>Hello World!!</h1>
<h2>My PieChart</h2>
<PieChart width={400} height={400}>
<Pie dataKey="value" isAnimationActive={false}
data={category}
cx="50%" cy="50%" outerRadius={80} fill="#8884d8"
label
/>
<Tooltip />
</PieChart>
</div>
);
}
export default App;
Also I have installed all the dependencies required but still pie chart is not created for the data which I have fetched from database.
Server.js :
const express = require("express");
const app = express();
const mysql = require('mysql');
const cors = require('cors');
app.use(cors());
app.use(express.json());
const db = mysql.createConnection({
user : 'root',
host : 'localhost',
password : 'password',
database : 'lab',
});
db.connect(function(err) {
if (err) throw err;
console.log("Connected!");
});
app.get('/posts', (req, res) => {
db.query("SELECT empname , empage FROM employee;", (err, results, fields) => {
if(err) throw err;
res.send(results);
});
});
app.listen(3001 ,(error)=>{
if (error) throw error ;
console.log("Server is running on port 3001");
})
When I hardcode data and try to display in pie chart then it works But it is not working when I am trying to display the data which I have fetched from database.

Getting JSON Object when the page is reloaded

I made an angular application and I made a NodeJS API which is running on different port from the angular application. I made a call to the API and displayed the returned JSON data on the gallery component which is a routed component. But when I reloaded the page I am only seeing my JSON data written but no gallery component. How can this be fixed? Thanks in advance!
This is my gallery component ts file.
import { DbConnectService } from '../db-connect.service';
interface GalleryItem {
path : String
}
#Component({
selector: 'app-gallery',
templateUrl: './gallery.component.html',
styleUrls: ['./gallery.component.css']
})
export class GalleryComponent implements OnInit {
galleryitem:any;
p:any = 1;
count: any = 2;
constructor(private gallery : DbConnectService) {
this.gallery.getgallery().subscribe((galleryitems) =>{
this.galleryitem= galleryitems;
})
}
ngOnInit(){
}
}
This is my API file
const bodyparser = require("body-parser")
const express = require("express");
const app = express();
const mysql = require("mysql");
app.use(bodyparser.json());
const conn = mysql.createConnection({
host:"localhost",
user:"root",
password:"",
database:"youngshoulders_gallery"
})
conn.connect((err)=>{
if(err) throw err;
console.log("mysql connected");
})
app.get("/gallery",(req,res)=>{
let sql = "SELECT * FROM GALLERY";
let query = conn.query(sql,(err,result)=>{
if(err) throw err;
res.send(result);
})
})
app.listen(8000);
This is the data returned when API is called
OUTPUT WHEN API IS CALLED
This is the returned JSON data after reloading the above page
JSON Output when page reloaded

How to make a PUT request to an Express application

I'm trying to create a web application using Angular and Node for study, but my PUT request isn't working even though my GET requests work. It seems like Node is ignoring the requests and I can't find why. In my app I try to edit the name of a user when clicking a button and I can see that the request works until it gets to the http client in users-service.service.ts.
users.component.html
<router-outlet></router-outlet>
<h3>Usuários</h3>
<table>
<tr><td>Nome</td></tr>
<tr *ngFor="let user of users"><td>{{user.first_name}}</td><td><button (click)="showUserInfo($event, user)">Editar</button></td></tr>
</table>
<br/><br/>
<div>
<label>First Name: </label><input type="text" value="{{user.first_name}}" (input)="user.first_name = $event.target.value">
<label>Last Name: </label><input type="text" value="{{user.last_name}}" (input)="user.last_name= $event.target.value">
<button (click)="updateUser()">Salvar</button>
</div>
<br/><br/>
<button (click)="loadAllUsers()">Reload</button>
users.component.ts
import { HttpClient, HttpClientModule } from '#angular/common/http';
import { UsersService, User } from './../users-service.service';
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'app-users',
providers: [UsersService, HttpClient, HttpClientModule],
templateUrl: './users.component.html',
styleUrls: ['./users.component.sass']
})
export class UsersComponent implements OnInit {
private users: User[];
private user: User = {first_name: '', last_name: '', id: null};
constructor(private service: UsersService) {
this.loadAllUsers();
}
ngOnInit() {}
showUserInfo(event, u : User) {
this.user = u;
}
loadAllUsers() {
this.service.getAllUsers().subscribe(valor => { this.users = valor as User[] });
}
updateUser() {
console.log(this.user);
this.service.updateUser(this.user);
}
}
users-service.service.ts
import { HttpClient, HttpClientModule, HttpHeaders } from '#angular/common/http';
import { Injectable } from '#angular/core';
import { Observable } from 'rxjs';
export interface User{
first_name: string,
last_name: string,
id: number
}
#Injectable()
export class UsersService{
constructor(private http: HttpClient) { }
getAllUsers(): Observable<User[]>{
return this.http.get<User[]>("http://localhost:4600/api/users");
}
updateUser(user: User): Observable<void>{
console.log('Updating: ' + user);
console.log("http://localhost:4600/api/users/" + user.id);
return this.http.put<void>("http://localhost:4600/api/users/" + user.id, user);
}
}
server.js
const express = require('express');
app = new express();
const morgan = require('morgan');
const cors = require('cors');
const mysql = require('mysql');
const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(morgan('dev'));
app.use('*', cors());
app.listen(4600, () => {
console.log("Server listening on port 4600...");
});
//All users
app.get("/api/users", (req, res) => {
let connection = getConnection();
connection.query('SELECT * FROM USERS', (err, result) => {
if(err){
throw err;
}
console.log(result);
res.json(result);
});
});
//Specific user
app.get('/api/users/:id', (req, res) => {
getConnection().query('SELECT * FROM USERS WHERE ID = ?', req.params.id, (err, result) => {
if(err){
console.log(err.message);
throw err;
}
res.json(result);
});
});
//Update user
app.put("/api/users/:id", (req, res) => {
console.log('PUT request received...');
getConnection().query("UPDATE USERS SET FIRST_NAME = ?, LAST_NAME = ? WHERE ID = ?", [req.body.first_name, req.body.last_name, req.body.id], (err, result) => {
if(err){
console.log(err.message);
throw err;
}
res.send(201, req.body);
});
});
//Delete user
app.delete('/api/users/:id', (req, res) => {
});
function getConnection(){
return mysql.createConnection({
host: 'localhost',
user: '',
password: '',
database: 'test'
});
}
EDIT 1
Based on #tadman comment I searched for the Network tools available in my browser and I found out, as expected, that the POST request were being ignored. By subscribing to the http client, the POST requests started to be noticed as they should. The answer by #KeaganFouche in the question bellow helped me:
Angular 4.0 http put request
New update method in the Angular service:
updateUser(user: User): void{
console.log('Updating: ' + user);
console.log("http://localhost:4600/api/users/" + user.id);
this.http.put<void>("http://localhost:4600/api/users/" + user.id, user).subscribe((response) => {console.log(response)});
}
Based on #tadman comment I searched for the Network tools available in my browser and I found out, as expected, that the POST request were being ignored. By subscribing to the http client, the POST requests started to be noticed as they should. The answer by #KeaganFouche in the question bellow helped me: Angular 4.0 http put request
New update method in the Angular service:
updateUser(user: User): void{
console.log('Updating: ' + user);
console.log("http://localhost:4600/api/users/" + user.id);
this.http.put<void>("http://localhost:4600/api/users/" + user.id, user).subscribe((response) => {console.log(response)});
}

Can't get data form nodejs by angular

Hi I can't get data from nodejs by angular 6.
I added a service to connect between them but it is not working.
I succeed to get data by nodejs server, but I can't receive it on angular components.
I know that I missed something to connect between them but I can't resolve it.
HostingstartComponent.ts
import { Component, OnInit } from '#angular/core';
import { NgAnalyzedFile } from '#angular/compiler';
import {RouterModule ,Routes } from '#angular/router';
import {HttpModule, Http} from '#angular/http'
import { AngularFontAwesomeModule } from 'angular-font-awesome';
import { SecComponent } from '../sec/sec.component';
import { ThirdComponent } from '../third/third.component';
import {aService} from '../services/a.service';
#Component({
selector: 'app-hostingstart',
templateUrl: './hostingstart.component.html',
styleUrls: ['./hostingstart.component.css']
})
export class HostingstartComponent implements OnInit {
aService: any;
data: any;
appRoutes : Routes=[
{path: 'hostingstar',component : HostingstartComponent},
{path: '',component : HostingstartComponent},
{path: 'sec',component : SecComponent, data : {some_data : 'some value'}},
{path: 'third',component : ThirdComponent, data : {some_data : 'some value'}}
];
headImg : any="assets/images/pan.JPG";
constructor(private http: Http , private service: aService) {
this.headImg ="assets/images/pan.JPG";
// this.aService.getData().then( (result) => {this.data = result; });
}
ngOnInit() {
// alert(this.aService.getData());
// this.aService.getData().then( (result) => {this.data = result; });
// alert(this.data);
}
myFunc() {
//this.router.navigate(['/third', 'north']);
// alert( document.getElementById("search-input").value);
}
getData() {
this.aService.getData().subscribe((dataFromServer) => {
this.data=dataFromServer;
// Now you can use the data
// alert(dataFromServer)
console.log(dataFromServer);
});
}
}
aService.ts
import 'rxjs/add/operator/toPromise';
import { Http, Response, Headers } from '#angular/http';
import { Injectable } from '#angular/core';
#Injectable()
export class aService {
constructor(private http: Http) {
}
async getData() {
const options = {
headers: new Headers({
'Content-Type': 'application/json;charset=utf-8',
'Access-Control-Allow-Origin': '*'
})
};
// const url = './assets/heroes.data.json';
const url = 'http://localhost:3000/';
return this.http.get(url, options)
.toPromise()
.then(response => {
if (response != null) {
const result = response.json();
return Promise.resolve(result);
}
return [];
})
.catch(err => {
console.warn('error in getCats', err);
return Promise.reject(null);
});
}
}
Node js : index.js
console.log('Running File: index.js')
//-- Create Express Server:
var express = require('express');
var app = express();
var util = require('util');
var mysql = require('mysql');
var a;
var con = mysql.createConnection({
host : 'localhost',
user: 'node',
password : 'arafat1990!##$',
database: "iTour"
});
con.connect(function(err) {
if (err) throw err;
con.query("SELECT * FROM feedback", function (err, result, fields) {
if (err) throw err;
// console.log(result);
a=result;
});
});
//-- Map Base URL to res (Response)
app.get('/', function(req, res){
var fname = req.query.fname;
var lname = req.query.lname;
var html = util.format('<p>Hello %s %s</p>', a[1].username,a[0].rating);
res.send(a);
});
app.get('/hostingstar', function(req, res){
var fname = req.query.fname;
var lname = req.query.lname;
var html = util.format('<p>Hello %s %s</p>', a[1].username,a[0].rating);
res.send(a);
});
//-- Listen on Port 3000:
app.listen(3000);
app.js
const express = require('express');
const app = express();
//const firebase = require('firebase-admin');
app.get('/hostingstart', (req, res) => res.send('Server Is Active!'))
app.get('/hostingstart', (req, res) => {
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user: 'node',
password : 'arafat1990!##$',
database: "iTour"
});
connection.connect();
connection.query('SELECT * FROM feedback;', function (error, results, fields) {
if (error) {
console.warn(error);
res.send('');
return;
}
console.log("Result: " + results);
res.send(results);
});
connection.end();
})
app.get('/hostingstart', (req, res) => {
var ref = firebase.app().database().ref();
ref.once("value").then(function (snap) {
console.log("snap.val()", snap.val());
res.send(snap.val());
});
});
app.use(function(req, res, next){
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Credentials", "true");
res.setHeader("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
res.setHeader("Access-Control-Allow-Headers", "Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers");
// Check if preflight request
if (req.method === 'OPTIONS') {
res.status(200);
res.end();
}
else {
next();
}
});
app.listen(3000, () => console.log('Server is listening on port 3000!'))
In your getService method you are calling the service itself not the property from the constructor.
Your:
this.aService.getData()
Should be:
this.service.getData()
Additionally call myFunc() in ngOnInit
ngOnInit() {
this.myFunc()
}

I am trying to display the data that i have inserted in mysql database. But the value is not being displayed

I want to display the name of the user that i have stored in my database. I am not able to retrieve any values. There is doesn't seem to be any error. I think i am not able to correctly access the database, But i can't figure out where i going wrong.
This is my react native code.
export default class UserProfile extends Component{
constructor(props)
{
super(props);
this.state={
name:'',
email:'',
}
};
componentWillMount() {
return this.getUser()
}
getUser(){
return fetch('http://192.168.0.20:3000/userprofile',{
method:'POST',
headers:{
'Accept':'application/json',
'Content-Type':'application/json',
}
body: JSON.stringify({
name: this.state.name,
})
})
.then((response) => response.json())
.then((responseData) => {})
}
render(){
console.disableYellowBox = true; //// to disable warning :)
return(
<Text> Username:{this.state.name}</Text> // trying to display name here.
);
}
}
This is my back-end code.
var express = require('express');
var router = express.Router();
var mysql = require('mysql');
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database:'backend',
})
/* our backend endpoint to check for users ian the database */
router.post('/', function(req, res, next) {
var name=req.body.name;
var phone=req.body.phone;
var email = req.body.email;
var password = req.body.password;
connection.query("SELECT * FROM user WHERE email = ? ",[email],function(err,row,fields){
console.log(name);
if (err) console.log(err);
});
});
module.exports = router;