Angularjs;在服务中使用$ http返回引用而不是实际数据

时间:2014-01-31 18:28:04

标签: angularjs object this angularjs-scope

我正在使用Angularjs not factory 中的services指令,我需要将json文件填充到本地变量中;

/* Contains projects on the town */
leMaireServicess.service('cityService', function($http) {

    // JSON regions and cities loader
    this.cities = [];

    // initCities 
    this.initCities = function() {
        this.cities = $http.get('data/census/cities.js').success(function(data) {
            return data;
        });
        return this.cities;
    };

    // Get city info
    this.getCity = function() {
        return this.cities;
    };
});

在我的控制器中我有

// Saved game controller
leMaireControllers.controller('GameCoreCtrl', function($scope, cityService) {

    /* Control the town project slides */
    cityService.initCities();
    $scope.city = cityService.getCity();

    console.log($scope.city);
});

但不是返回实际数据,而是返回;

Object {then: function, catch: function, finally: function, success: function, error: function}

3 个答案:

答案 0 :(得分:6)

您可以使用手表来完成这项工作(see plunker

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope,cityService) {
  //$scope.cities = [];
  $scope.service = cityService;
  cityService.initCities();


  $scope.$watch('service.getCity()', function(newVal) {
    $scope.cities = newVal;
    console.log(newVal)
  });


});

app.service('cityService', function($http) {
  var that = this;
  this.cities = [];

  this.initCities = function() {
      $http.get('data.js').success(function(data) {
          that.cities = data.cities;
      });
  };

  this.getCity = function() {
      return this.cities;
  };
});

答案 1 :(得分:3)

$ http返回一个promise,这就是你要将this.cities设置为。

这可能有助于解释更多, https://stackoverflow.com/a/12513509/89702

在你的控制器中你应该可以做这样的事情......

cityService.initCity().then(function(data) { $scope.city = data; }

答案 2 :(得分:1)

您正在使用promises,它代表异步执行的操作的结果。试试这种方式:

leMaireServicess.service('cityService', function($http) {

    this.promise = {};

    // initCities 
    this.initCities = function() {
        this.promise = $http.get('data/census/cities.js');
    };

    // Get city info
    this.getCity = function() {
        return this.promise;
    };
});

在控制器中,您需要将代码置于回调中:

// Saved game controller
leMaireControllers.controller('GameCoreCtrl', function($scope, cityService) {

    /* Control the town project slides */
    cityService.initCities();
    cityService.getCity().then(function(result){
        $scope.city = result.data;
        console.log($scope.city);
    });

});