0

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".

1 Answers1

0

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);
});
Leandro Zubrezki
  • 1,150
  • 9
  • 12
  • That's what im searching for! But now "members"-function isn't called. Instead it throws the error "TypeError: Cannot read property 'then' of undefined"?! – Sebastian Ortmann Nov 25 '15 at 12:04
  • Instead of using a switch statement just add a getAll method and return from there. – Leandro Zubrezki Nov 25 '15 at 12:06
  • I know what you mean, but i can't get it work :( can you give me a hint, how to define a method "getAll" in the function "members", please? And how can i call it? moduleService.members.getAll() ? – Sebastian Ortmann Nov 25 '15 at 13:29
  • Okay thank you! Instead of using a **getAll** method in the **members** function, i renamed **moduleService** to **moduleServiceMembers** and the **members** function is now the **getAll** function. – Sebastian Ortmann Nov 25 '15 at 15:50
  • Perfect! Let me know if you need more help! – Leandro Zubrezki Nov 25 '15 at 21:31