简体   繁体   中英

AngularJS: Get $http response from function in module

how do i get the response from $http in from a function in a module?

Angular module:

// 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;
      }

    },

  };

});

Controller:

myApp.controller('main', ['$scope', '$http', 'moduleService', function($scope, $http, moduleService){

  $scope.handleClick = function () {

    var ReturnValue = moduleService.members({
      fc:'getAll',
      id:'123',
    });

    console.log(ReturnValue);

  };

}]);

the object is on the first click empty and on the second click its content is the $http response.

but i want that the controller knows when the $http response is available.

i tried to use $broadcast and $on, but it seems to be impossible to use $rootScope in my function "sendRequest".

A couple of things:

Why are you defining the httpResponse instead of just returning something from the sendRequest function?

Why are you defining a function outside angular instead of putting it as a service or factory?

You should create a service with the sendRequest method inside like this:

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

Then in the other service:

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

    },

  };

});

Now the result will be a promise, so you can consume the data like this:

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

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