Search code examples
angularjsasynchronousresponse

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');
};

Solution

  • Some points:

    • take into consideration, when you received one response from $http it's the common response (with status, headers, etc). So, if you want to access your data you will have to do: response.data

    • Usually, when you have a service, you define multiple endpoints. So, you can return an object with multiple requests.

    Check this little sample working: 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' }
            });      
        }
      })
    })
    

    And the controller is as simple as:

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