我正在加载Google地图,当我导航到/地图时,它会加载标记以填充地图。问题是JavaScript的其余部分在加载标记之前运行并执行。我认为解决这个问题的方法是在检索地图数据的工厂返回一个承诺。这虽然没有奏效。我的角厂承诺有什么问题?
任何人都可以建议我做错了什么?
在控制台中我看到这一点:
angular.js:13920 TypeError: Cannot read property 'lat' of undefined
at Object.link (http://localhost/logintest/js/app.js:586:55)
586线是指这条线(该指令):
center: new google.maps.LatLng(lastElement.lat, lastElement.lon),
我得到了lastElement
像这样:
var lastElement = scope.arrLocations[scope.arrLocations.length - 1];
工厂:
app.factory('map', ['$q', function($q){
var map={};
var mapInfoItems=[];
map.getMapInfo = function() {
var deferred = $q.defer();
var mapitems = firebase.database().ref('mapinfo/'+firebase.auth().currentUser.uid);
mapitems.on('child_added', function(snapshot){
mapInfoItems.push(snapshot.val());
deferred.resolve(mapInfoItems);
});
return deferred.promise;
};
return map;
}]);
控制器:
app.controller('mapController', ['$scope', 'map', function($scope, map){
$scope.myLocations = {};
$scope.arrLocations = [];
$scope.mapLocations = map.getMapInfo();
for(var i=0; i<$scope.mapLocations.length; i++){
$scope.myLocations.title = $scope.mapLocations[i].name;
$scope.myLocations.content = $scope.mapLocations[i].message;
$scope.myLocations.lat = $scope.mapLocations[i].lat;
$scope.myLocations.lon = $scope.mapLocations[i].lon;
$scope.arrLocations.push($scope.myLocations);
}
}]);
HTML:
<div ng-controller="mapController">
<my-map get-map-fn="getMap()"></my-map>
</div>
是什么控制台说? –
我已经添加了更多的细节。 – user1532669
好吧,所以'arrLocations'的创建有些问题。让我们在控制台中记录前一步,看看它的样子。也许'console.log($ scope.myLocations);' –