AngularJS:从模块中的函数获取$http响应

AngularJS: Get $http response from function in module

本文关键字:获取 http 响应 函数 模块 AngularJS      更新时间:2023-09-26

如何从模块中的函数获得$http in的响应?

角度模块:

// module customServices
var customServices = angular.module("customServices", []);
// object for response
httpResponse = {content:null};
// function sendRequest
function sendRequest(param)
{
  // inject $http
  var initInjector = angular.injector(['ng']);
  var $http = initInjector.get('$http');
  // set header
  $http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
  $http({
    // config
    method: 'POST',
    url: 'response.php',
    data: $.param(param),
    // success
    }).success(function (response, status, headers, config) {
      httpResponse.content = response;
    // error
    }).error(function (response, status, headers, config) {
      console.warn("error");
    });
}
// factory - moduleService
customServices.factory("moduleService", function () {
  return {
    // function - members
    members: function(param)
    {
      switch(param.fc)
      {
        // getAll
        case 'getAll':  
          sendRequest({
            service :'members',
            fc      : param.fc,
            id      : param.id
        });
        return httpResponse;
      }
    },
  };
});

控制器:

myApp.controller('main', ['$scope', '$http', 'moduleService', function($scope, $http, moduleService){
  $scope.handleClick = function () {
    var ReturnValue = moduleService.members({
      fc:'getAll',
      id:'123',
    });
    console.log(ReturnValue);
  };
}]);

第一次单击时对象为空,第二次单击时其内容为$http响应。

但是我希望控制器知道$http响应何时可用。

我尝试使用$broadcast和$on,但似乎不可能在函数"sendRequest"中使用$rootScope。

两件事:

为什么要定义httpResponse,而不只是从sendRequest函数返回一些内容?

为什么要在angular之外定义一个函数,而不是将其作为服务或工厂?

您应该创建一个内部带有sendRequest方法的服务,如下所示:

customServices.factory("yourNameHere", function($http, $q) {
  $http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
  return {
    sendRequest: function sendRequest(param) {
      return $http({
          method: 'POST',
          url: 'response.php',
          data: $.param(param),
        })
        .then(function(response) {
         return response;
        })
        .catch(function(response) {
          console.warn("error");
          return $q.reject(response);
        });
    }
  };
});

然后在另一项服务中:

customServices.factory("moduleService", function (yourNameHere) {
  return {
    // function - members
    members: function(param)
    {
      switch(param.fc)
      {
        // getAll
        case 'getAll':  
          return yourNameHere.sendRequest({
            service :'members',
            fc      : param.fc,
            id      : param.id
        });
      }
    },
  };
});

现在的结果将是一个承诺,所以你可以这样消费数据:

moduleService.members({
  fc:'getAll',
  id:'123',
})
.then(function(result) {
    console.log(result);
});