将服务数据保存到控制器的全局变量中

Saving Service Data To Global Variable in Controller

本文关键字:全局变量 控制器 服务 数据 保存      更新时间:2023-09-26

我无法在位置内更新geodata数组。成功的功能。console.log在函数内部打印JSON对象,但在函数外部未定义。

我想在函数调用之外访问geodata数组内容。任何代码片段都会有帮助。

app.controller('MainController', ['$scope','places', function($scope,places)     {
  $scope.mapCenter = {
  lat: 40.741934,
  lng: -74.004897,
  zoom: 17
  };
  var geodata=new Array();
  places.success(function(data) {
     geodata = data;
     console.log('inside'+geodata); //geodata is having a json value here, returning from data. 
   });
   console.log(geodata); //why geodata is still undefined here, I assigned value 
   }]);

解决问题:

app.controller('MainController', ['$scope','places', function($scope,places)     {
  $scope.mapCenter = {
      lat: 40.741934,
      lng: -74.004897,
      zoom: 17
    };
  var geodata=new Array();
  var callme=function(data){
    console.log('call'+data)
    $scope.mapMarkers = geodataToMarkers(data)
  }
  places.success(function(data) {
    geodata = data
    console.log('inside'+data); //geodata is having a json value here, returning from data. 
    callme(data);
  });
 }]);

因为位置。成功是异步的,在调用这个方法后,它移动到console.log(geodata),它将打印空数组而不是null。您必须等待拥有数据的响应。

app.controller('MainController', ['$scope','places', function($scope,places)     {
  $scope.mapCenter = {
  lat: 40.741934,
  lng: -74.004897,
  zoom: 17
  };
  var geodata=new Array();
  places.success(function(data) {
     geodata = data;
      console.log('inside'+geodata); //You can receive here data
   });
    // console.log(geodata); Because places.success is asycnronous, its the empty array not null
   }]);

假设有一个指令(例如my-marker)在地图上显示地理位置,您可以在模板html中使用ng-repeat来运行geodata变量。因此,您应该在控制器范围内定义它。

控制器代码片段

$scope.geodata = [];
places.success(function (data) {
  $scope.geodata = data; //Note depending on how your promise is resolved you may have to do **data.data** instead of **data**
});
模板

<my-marker ng-repeat="geoDatum in geoData" geo-datum="geoDatum"></my-marker>

注意:我已经根据你的指示做出了陈述性的假设。

在您的服务中保存数据(来自您的评论),如下所示:

app.service('places', ['$http', function($http) {
  this.dataFromService = []; 
  this.getData = function(){
   return $http.jsonp('en.wikipedia.org/w/…') .success(function(data) { 
     this.dataFromService = data; }); 
   }
}
]);

然后在你的控制器中调用服务,然后在promise被解析后使用.then()来访问数据:

app.controller('MainController', ['$scope','places', function($scope,places)     {
  $scope.mapCenter = {
  lat: 40.741934,
  lng: -74.004897,
  zoom: 17
  };
  var geodata=new Array();
  places.getData().$promise.then(function(){
  geodata = this.dataFromService;
  });
  console.log(geodata);
}]);

更多参考:http://weblog.west-wind.com/posts/2014/Oct/24/AngularJs-and-Promises-with-the-http-Service