2017-04-08 80 views
-1

如何將所有這些一起使用?例如,我有一個帶有一個表(ID,文本,完成)的簡單數據庫和一個將數據從mySQL導出到JSON文件的代碼。 JSON文件看起來像:angular + node(express)+ mysql

[{ "id":"1", "text":"learn angular", "done":true }, 
{ "id":"2", "text":"build an angular app", "done":false}] 

而且server.js文件:

var fs = require('fs'); 
var serverUrl = 'localhost'; 
var port = 3000; 
var path = require('path'); 
var express = require('express'); 
var app = express(); 
var http = require('http').Server(app); 
var mysql = require('mysql'); 
var bodyParser  = require('body-parser'); 
var methodOverride = require('method-override'); 
app.use(bodyParser.json()); // parse application/json 
app.use(bodyParser.json({ type: 'application/vnd.api+json' })); 
app.use(bodyParser.urlencoded({ extended: true })); 
app.use(methodOverride('X-HTTP-Method-Override')); 
app.use(express.static(__dirname + '/public')); 
require('./app/routes')(app); // pass our application into our routes 
app.get('/', function(req, res){ 
res.sendfile('public/index.html'); 
}); 

var connection = mysql.createConnection({ 
    host : 'localhost', 
    user : 'root', 
    password : '', 
    database : 'todos', 
}); 

connection.connect(); 

app.get('/',function(request,response){ 
connection.query('SELECT * FROM todos', function(err, rows, fields, res) 

{ 
     console.log('Connection result error '+err); 
     console.log('no of records is '+rows.length); 
     response.writeHead(200, { 'Content-Type': 'application/json'}); 
     response.end(JSON.stringify(rows)); 
     }); 

app.set('port', 3000); 

http.listen(port, function(){ 
console.log('listening on: ' + app.get('port')); 
}); 

exports = module.exports = app; 

我應該怎麼做?我如何使用從angularjs應用程序從mysql導出到JSON數據? index.html文件:

<!doctype html> 
<html lang="en"> 
<head> 
<meta charset="UTF-8"> 
<base href="/"> 

<title></title> 

<!-- CSS --> 

<!-- JS --> 

<!-- ANGULAR CUSTOM --> 
</head> 

<body ng-app="App" ng-controller="Controller"> 
<div class="someClass"> 
<table> 
<tr> 
    <th>id</th> 
    <th>text</th> 
    <th>done</th> 
</tr> 
<tr ng-repeat="todo in todos"> 
    <td>{{todo.id}}</td> 
    <td>{{todo.text}}</td> 
    <td>{{todo.done}}</td> 
</tr> 
</table> 
<div> 
</body> 
</html> 

我理解正確的整個機制嗎?我們在mysql中有一些數據庫,將mysql數據轉換成json對象,然後用角度讀取這些對象?如果是這樣,那麼我們如何才能用數據庫執行crud操作?預先感謝任何意見和答案,這將有助於我理解它。

+0

爲獲取數據到您的角度應用程序您需要使用角度$ HTTP服務進行ajax調用請閱讀此處:https://docs.angularjs.org/api/ng/service/$http – happyZZR1400

回答

0

您可以使用$ http serveice從API獲取值。例如:

$http({ 
    method: "POST", 
    url: "youUrl", 
    data: { "foo": "bar", "baz": "moe" }, 
    headers: {'Content-Type': 'application/json'} //optional 
}).then(function(response){ 
    console.log(response) // success function 
}, function(err){ 
    console.log(err) // error function 
}); 

響應將包含您從後端發送的API數據。

+0

仍然不明白如何給出可以與角度一起使用的數據。例如,我有以下代碼:$ scope.getTodos =函數(){ \t變種的HttpRequest = $ HTTP({ \t \t方法: 'POST', \t \t URL: '../todos.json', ?\t \t數據:這裏應該是什麼 \t})成功(功能(數據,狀態){ \t \t $ scope.todos =數據; \t}); }; – Kirill

+0

@Kirill請看看答案 –