在服务上发出http请求,在控制器中获取响应

时间:2021-05-02 16:54:49

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.

我正在使用服务为本地JSON文件发出http请求。我正在尝试将成功的HTTP请求中的数据存储在我的控制器中,但该部分无效。然而,http请求似乎在服务上是成功的。

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

4 个解决方案

#1


4  

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

您没有从服务方法返回任何内容。返回$ http promise并在控制器中使用then()将返回的数据分配给controller属性。您还没有在控制器中定义self

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

#2


0  

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){

});

#3


0  

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

你应该在$ http.get()之后返回一个promise。然后(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.

在您的代码中被限制并“限定”到successCallback。因此,为了获得它的句柄,您需要返回与successCallback相关联的promise。

         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.

console.log输出表示执行的代码,但返回的theData在没有与之关联的承诺的情况下是没有用的。

In the controller:

在控制器中:

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

A working plunkr here

这是一个工作的傻瓜

#4


0  

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!");
       })
    };
});

#1


4  

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

您没有从服务方法返回任何内容。返回$ http promise并在控制器中使用then()将返回的数据分配给controller属性。您还没有在控制器中定义self

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

#2


0  

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){

});

#3


0  

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

你应该在$ http.get()之后返回一个promise。然后(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.

在您的代码中被限制并“限定”到successCallback。因此,为了获得它的句柄,您需要返回与successCallback相关联的promise。

         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.

console.log输出表示执行的代码,但返回的theData在没有与之关联的承诺的情况下是没有用的。

In the controller:

在控制器中:

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

A working plunkr here

这是一个工作的傻瓜

#4


0  

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!");
       })
    };
});