[英]Getting http.get data into local JSON array variable
I am very new to Angular and Nodejs and thought this would be a fun project to try. 我对Angular和Nodejs非常陌生,并认为这是一个有趣的尝试项目。 I am trying to get the the json data from the http.get
in angular.js and put it into a variable cities so it can display on the google maps. 我正在尝试从http.get
中的http.get获取json数据,并将其放入可变城市中,以便它可以显示在Google地图上。
When I try to console.log(cities);
当我尝试console.log(cities);
it returns an object but console.log(cities.items)
returns and undefined; 它返回一个对象,但console.log(cities.items)
返回console.log(cities.items)
定义;
When i try to see the if i can JSON.stringify
the data inside the $http.get
it display the data below which is what i am trying to accomplish. 当我尝试查看是否可以JSON.stringify
$http.get
的数据时,它显示下面的数据,这正是我要完成的工作。 Is there another way to get this data into the var cities so i can use it as shown below? 还有另一种方法可以将这些数据输入到var城市,以便我可以如下所示使用它?
{
"city": "New York",
"state": "NY",
"desc": "Google NYC",
"lat": 40.7418,
"long": -74.0045
}
Any help is greatly appreicated 非常感谢任何帮助
angular.js angular.js
//Angular App Module and Controller
var sampleApp = angular.module('mapsApp', []);
var cities = $http.get('/locations').success(function (data){
$scope.items = data.items;
})
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(41.5, -73),
mapTypeId: google.maps.MapTypeId.TERRAIN
}
$scope.map = new google.maps.Map(document.getElementById('map'), mapOptions);
$scope.markers = [];
var infoWindow = new google.maps.InfoWindow();
var createMarker = function (info) {
var marker = new google.maps.Marker({
map: $scope.map,
position: new google.maps.LatLng(info.lat, info.long),
title: info.city
});
marker.content = '<div class="infoWindowContent">' + info.desc + '</div>';
google.maps.event.addListener(marker, 'click', function () {
infoWindow.setContent('<h2>' + marker.title + '</h2>' + marker.content);
infoWindow.open($scope.map, marker);
});
$scope.markers.push(marker);
}
for (i = 0; i < cities.length; i++) {
createMarker(cities[i]);
}
$scope.openInfoWindow = function (e, selectedMarker) {
e.preventDefault();
google.maps.event.trigger(selectedMarker, 'click');
}
});
googleMaps.html googleMaps.html
<!DOCTYPE html>
<html ng-app="mapsApp">
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<link rel="stylesheet" href="css/maps.css">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.3/angular.min.js"> </script>
<script
src="http://maps.googleapis.com/maps/api/js?sensor=false&language=en"></script>
<script type="text/javascript" src="js/maps.js"></script>
</head>
<body>
<div ng-controller="MapCtrl">
<div id="map"></div>
<div id="repeat" ng-repeat="marker in markers | orderBy : 'title'">
<a id="country_container" href="#" ng-click="openInfoWindow($event, marker)">
<label id="names" >{{marker.title}}</label></a>
</div>
<ul>
<li ng-repeat="item in items">
{{item}}
</li>
</ul>
</div>
</body>
</html>
app.js app.js
//Rest HTTP stuff
var express = require('express');
var bodyParser = require('body-parser');
var dbGoogle = require('./dbGoogle');
var app = express();
// configure body parser
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
var port = process.env.PORT || 8080; // set our port
// create our router
var router = express.Router();
// middleware to use for all requests
router.use(function (req, res, next) {
// do logging
console.log('Incoming request..');
next();
});
// test route to make sure everything is working
router.get('/', function (req, res) {
res.json({message: 'Welcome!'});
});
router.route('/locations')
// get all the locations
.get(function (req, res) {
dbGoogle.getGoogles(function (err, data) {
if (data) {
res.json({
status: '200',
items: data
});
} else {
res.json(404, {status: err});
}
});
})
// Register routes
app.use('', router);
//Serve static content files
app.use(express.static('public'));
// START THE SERVER
app.listen(port);
console.log('Running on port ' + port);
db.js db.js
var mysql = require('mysql');
var app = require('./app.js');
var pool = mysql.createPool ({
host: 'localhost',
user: 'root',
port: 3306,
password: 'password',
database: 'testdb'
});
module.exports.pool = pool;
pool.getConnection(function(err){
if(!err) {
console.log("Database is connected\n\n");
} else {
console.log(err);
}
});
dbGoogle.js dbGoogle.js
var db = require('./db.js');
var getGoogles = function getGoogles(callback) {
db.pool.getConnection(function (err, connection) {
// Use the connection
connection.query('SELECT * FROM locations', function(err, results){
if (!err) {
if (results != null) {
callback(null, results);
} else {
callback(err, null);
}
} else {
callback(err, null);
}
//release
connection.release();
});
});
}
module.exports.getGoogles = getGoogles;
Try to create the markers asynchronous, something like 尝试创建异步标记,例如
$http.get('/locations').success(function (data){
angular.forEach(data.items, function(item) {
createMarker(item);
});
})
because $http.get
returns promise object.. so when you assign the $http.get
to cities its not the data returned by the server its just the promise object.. what you have done right is in your success
callback where you did $scope.items = data.items;
因为$http.get
返回$http.get
对象..所以当您将$http.get
分配给城市时,它不是服务器返回的数据,它只是$http.get
对象..您正确执行的操作是在执行$scope.items = data.items;
success
回调中$scope.items = data.items;
this is the callback
where you get the data from the server.. welcome to the world of Async 这是您从服务器获取数据的callback
。. 欢迎来到异步世界
one solution could be to put all your code that uses cities.items
inside success
callback but it'll be a dirty code. 一种解决方案是将所有使用cities.items
的代码放入success
回调中,但这将是肮脏的代码。 But you get the idea.. 但是你明白了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.