【发布时间】: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