【问题标题】:AngularJS: Get $http response from function in moduleAngularJS:从模块中的函数获取 $http 响应
【发布时间】:2016-02-28 00:38:42
【问题描述】:

如何从模块中的函数中获取来自 $http 的响应?

角度模块:

// 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 似乎是不可能的。

【问题讨论】:

    标签: javascript angularjs callback asynccallback


    【解决方案1】:

    有几点:

    你为什么要定义 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);
    });
    

    【讨论】:

    • 这就是我正在寻找的东西!但是现在没有调用“成员”函数。相反,它会抛出错误“TypeError:无法读取未定义的属性'then'”?!
    • 不使用 switch 语句,只需添加一个 getAll 方法并从那里返回。
    • 我知道你的意思,但我不能让它工作:(你能给我一个提示,如何在函数“members”中定义一个方法“getAll”,好吗?以及如何我可以调用它吗?moduleService.members.getAll() ?
    • 好的,谢谢!我没有在 members 函数中使用 getAll 方法,而是将 moduleService 重命名为 moduleServiceMembersmembers 函数现在是 getAll 函数。
    • 完美!如果您需要更多帮助,请告诉我!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-10
    • 1970-01-01
    • 2017-11-25
    • 2022-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多