将数据从服务传递到控制器&在Angular中查看

时间:2015-10-01 06:38:31

标签: json angularjs model-view-controller

我正在尝试在我的视图中显示数据。 我有一个名为$this->property的服务:

"LocationService"

我有一些虚拟控制器:

.factory('LocationService', function($resource, $http, $rootScope) {
  return {
    'getAvailableLocations': function() {
      $http.get('/api/v1/locations/available').success(function(response) {
        console.log(response); //logs proper response with json
        return response;
      });
    }
  }
});

我确信该服务获得了正确的响应。但是,当我尝试在模板中显示它(或从控制器发出警报)时,我得到了.controller('DummyCtrl', function($scope, $timeout, $state, $http, $stateParams, LocationService) { $scope.available_locations = LocationService.getAvailableLocations(); alert($scope.available_locations); // alerts undefined })

我该如何解决这个问题?

3 个答案:

答案 0 :(得分:4)

您的代码应该类似于:

myApp.factory('LocationService', function($http){
    return {
        getAvailableLocations: function(){
            return $http.get('/api/v1/locations/available');
        }
    }
});

myApp.controller('DummyCtrl', function($scope, LocationService){
    LocationService.getAvailableLocations().then(function(locations){
        $scope.available_locations = locations;
    });
});

与您的代码不同的东西:

  1. 该服务现在返回一个使用响应中的位置解析的承诺(在您的代码中,方法getAvailableLocations没有返回任何内容)。

  2. 控制器处理promise并将结果绑定到作用域上的available_locations属性。

答案 1 :(得分:2)

那是因为方法getAvailableLocations()是异步的。它使用$http.get返回一个promise。

你的解决方案是:

'getAvailableLocations': function() {
  var promise = $http.get('/api/v1/locations/available').success(function(response) {
    console.log(response); //logs proper response with json
    return response;
  });

  return promise;
}

controller('DummyCtrl', function($scope, $timeout, $state, $http, $stateParams, LocationService) {

  function getLocations() {
    var promise = LocationService.getAvailableLocations();

    promise.then(function(response) {
      $scope.available_locations = response.data;
      alert($scope.available_locations);
    });
  }

  getLocations();
});

答案 2 :(得分:0)

LocationService

.factory('LocationService', function ($resource, $http, $rootScope) {
    return {
        'getAvailableLocations': function () {
            return $http.get('/api/v1/locations/available');
        }
    };
});

<强> DummyCtrl

.controller('DummyCtrl', function ($scope, $timeout, $state, $http, $stateParams, LocationService) {
    LocationService.getAvailableLocations().then(function (response) {
        $scope.available_locations = response.data;
    }, function (response) {
        console.log("Error: " + response.statusText); // If you need to show error message.
    });
});