繁体   English   中英

将http.get数据获取到本地JSON数组变量中

[英]Getting http.get data into local JSON array variable

我对Angular和Nodejs非常陌生,并认为这是一个有趣的尝试项目。 我正在尝试从http.get中的http.get获取json数据,并将其放入可变城市中,以便它可以显示在Google地图上。

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

当我尝试查看是否可以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;

尝试创建异步标记,例如

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

因为$http.get返回$http.get对象..所以当您将$http.get分配给城市时,它不是服务器返回的数据,它只是$http.get对象..您正确执行的操作是在执行$scope.items = data.items; success回调中$scope.items = data.items; 这是您从服务器获取数据的callback 。. 欢迎来到异步世界

一种解决方案是将所有使用cities.items的代码放入success回调中,但这将是肮脏的代码。 但是你明白了。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM