简体   繁体   中英

Make an http request on a service, get response in controller

I'm making an http request for a local JSON file using a Service. I'm trying to store the data from the successful HTTP request in my controller but that part is not working. The http request does however seem to be successful on the Service.

var myModule = angular.module("MyApp", [])

  .controller('MyController', function(Utilities){

     //this is not working
     self.socialArr = Utilities.getData("data.json");

   }).service('Utilities', function($http) {

     var self = this;

     self.getData = function(jsonData) {
       $http.get(jsonData)
        .then(function(response) {
            //First function handles success
            var theData = response.data;
            console.log(theData); //this works (data is logged)
            return theData;
        }, function(response) {
            //Second function handles error
            console.log("Error loading JSON data");
        });
     };
 });

You aren't returning anything from the service method. Return the $http promise and use then() in controller to assign the returned data to controller property. Also you haven't defined self in controller

angular.module("MyApp", [])

.controller('MyController', function(Utilities) {
  // store reference of "this"
  var self = this;
  // call service method
  Utilities.getData("data.json").then(function(data) {
    // assign data after promise resolves
    self.socialArr = data;
  });


}).service('Utilities', function($http) {

  var self = this;

  self.getData = function(jsonData) {
    // return the promise
    return $http.get(jsonData).then(function(response) { 
        return response.data;
      }, function(response) {
        //Second function handles error
        console.log("Error loading JSON data");
      });
  }
});

I think You should be using a promise.because you are making an asyncronous call.

 self.getData = function(jsonData) {
var deferred = $q.defer();
       $http.get(jsonData)
        .then(function(response) {

            if (response.data) {
      deferred.resolve(response);
    } else {
      deferred.reject(response);
    }

        }, function(response) {
            deferred.reject(response);
        });
 return deferred.promise;
     };

then in the controller

 Utilities.getData("data.json").then(function(res)
{
   self.socialArr=res;
},function(e){

});

You should return a promise after the $http.get().then(successCallback);

The return statement,

 return theData;

in your code is confined and "scoped" to the the successCallback. So in order to get a handle to it, you need to return the promise associated that the successCallback is part of.

         self.getData = function(jsonData) {

         // store the promise
         var promise = $http.get(jsonData)
        .then(function(response) {
            //First function handles success
            var theData = response.data;
            console.log(theData); //this works (data is logged)
            return theData;
        });

        // return the promise, which can get you the successCallback's    returned data.
        return promise;
      };        

The console.log output means the code executed, but the returned theData is no use without the promise it associated with.

In the controller:

          Utilities.getData("data.json").then(function(socialArr){
            $scope.socialArr = socialArr;
            // this should print
            console.log($scope.socialArr);
          });

A working plunkr here

var myModule = angular.module("MyApp", [])

.controller('MyController', function(Utilities){

     Utilities.getData("data.json").success(function(responce) {
         self.socialArr = response.data;
     })

 })
.service('Utilities', function($http) {

    var self = this;

    self.getData = function(jsonData) {
       return $http.get(jsonData).error(function(responce) {
           console.log("error!");
       })
    };
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM