如何在 angularjs 中将 http 数据从服务传递到控制器

how to pass http data from service to controller in angularjs

var locationListCtrl=function($scope, loc8rData){
 $scope.message = "Searching for nearby places";
   loc8rData
      .success(function(data){$scope.message = data.length > 0 ? "" : "No locations Found";
        $scope.data = { locations: data };
     })
      .error(function(e){
        $scope.message = "Sorry, Something has gone wrong";
        console.log(e);
     });
};

var loc8rData = function ($http){
  

     return $http.get('/api/locations?lng=33.7741195&lat=-13.9626121&maxDistance=20');
};

几点:

  • 考虑到,当您收到来自 $http 的一个回复时,这是常见的回复(带有状态、headers 等)。所以,如果你想访问你的数据,你必须这样做:response.data

  • 通常,当您拥有一项服务时,您会定义多个端点。因此,您可以 return 一个具有多个请求的 object。

检查这个小示例是否正常工作:https://plnkr.co/edit/FNxEeVZti6D1wmLe

.service('PokeApi', function($http) {
  return ({
    getPokemon: function (name) {
        return $http({
          method: 'GET',
          url: 'https://pokeapi.co/api/v2/pokemon/' + name,
          headers: { 'Content-Type': 'application/json' }
        });      
    }
  })
})

而控制器就这么简单:

.controller('MainCtrl', function($scope, PokeApi) {
  $scope.name = 'Plunker';
  PokeApi.getPokemon('pikachu').then(function (response) {
    $scope.pokemon =  response.data;
  });
});