AngularJS:从模块中的函数获取$http响应
AngularJS: Get $http response from function in module
如何从模块中的函数获得$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);
});
相关文章:
- AngularJS:如何获取$http结果作为函数的返回值
- 在javascript中获取 http.post,然后发送响应
- 如何通过JavaScript获取HTTP协议版本
- 使用C++获取HTTP get参数
- AngularJS无法从PHP获取HTTP标头
- 尝试在火狐扩展中获取 HTTP POST 请求
- 获取 http://localhost//images/Products/ 403(禁止)
- 在节点.js中获取 http 状态代码
- jQuery$.从https站点获取http
- Chrome扩展-如何获取HTTP响应正文
- 如何通过JS|Jquery获取HTTP Referer
- AngularJS:如何获取$http的错误状态
- 如何获取HTTP get请求传递的客户端参数
- 在jquery中获取http状态代码
- 如何使用JS获取HTTP响应头
- 使用$q.all()从AngularJS中的函数获取$http数据
- AngularJS:从模块中的函数获取$http响应
- 在Node.js中使用restler获取HTTP响应
- 获取HTTP内容
- AngularJS:获取$http.在JSP中发布数据