将http.get数据转换为本地JSON数组变量

时间:2015-12-14 04:36:18

标签: javascript angularjs json node.js

我是Angular和Nodejs的新手,并认为这将是一个有趣的项目。我试图从angular.js中的http.get获取json数据并将其放入变量城市,以便它可以显示在谷歌地图上。

当我尝试console.log(cities);时,它返回一个对象,但console.log(cities.items)返回并且未定义;

当我试图看到{i} JSON.stringify $http.get内的数据时,它会显示下面的数据,这正是我想要完成的。还有另一种方法可以将这些数据输入var城市,以便我可以使用它,如下所示吗?

    {
      "city": "New York",
      "state": "NY",
      "desc": "Google NYC",
      "lat": 40.7418,
      "long": -74.0045
    }

任何帮助都非常有用

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

<!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

//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

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

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;

2 个答案:

答案 0 :(得分:2)

尝试创建异步标记,例如

$http.get('/locations').success(function (data){
    angular.forEach(data.items, function(item) {
        createMarker(item);
    });
})

答案 1 :(得分:1)

因为$http.get返回了promise对象..所以当你将$http.get分配给城市时,它不是服务器返回的数据,只是承诺对象..你做得对的是你的{ {1}}回调你success的回调这是从服务器获取数据的$scope.items = data.items; .. 欢迎来到异步世界

一种解决方案可能是将所有使用callback的代码放在cities.items回调中,但它应该是一个脏代码。但你明白了......