[英]AngularJS Async request method service return data using promise
我在定制服务中有这种全局方法。
/**
* Global service class for making http requests.
*/
app.service('API', function ($http) {
/**
* Process remote POST request to give URL with given params
* @param {String} url
* @param {String} POST params
* @return {JSON} response from server
*/
this.doHttpRequest = function (type, url, params) {
$http({
method: type,
url: url,
data:params,
timeout:2000,
headers: {"Content-Type": "application/json"}
})
.success(function (data, status, headers, config) {
// successful data retrieval
console.log("request success");
console.log("state: "+status);
return data;
})
.error(function (data, status, headers, config) {
// do some stuff
});
};
});
||
问题是,如果我试图从我的cotroler方法获得响应,那么我总是总是不确定的。
/**
* Test of service
*/
$scope.serviceTest = function () {
var requestParams = {
"token":'test',
"data":{
"test":'test'
}
};
var url = $rootScope.apiBaseUrl + "user/update";
var result = API.doHttpRequest("POST", url, requestParams);
// HERE I GET UNDEFINED
console.log("Result is: " + result);
};
我对诺言感到不满,但没有运气来取回数据。
问题是:
我应该如何修改我的代码以获得返回值?
谢谢你的帮助
修改您的服务,使其不会在$http
返回的promise
上调用任何内容,也请注意return
。
app.service('API', function ($http) {
/**
* Process remote POST request to give URL with given params
* @param {String} url
* @param {String} POST params
* @return {JSON} response from server
*/
this.doHttpRequest = function (type, url, params) {
return $http({
method: type,
url: url,
data:params,
timeout:2000,
headers: {"Content-Type": "application/json"}
});
};
});
然后,当您使用服务时,它将返回一个promise
,您可以在该promise
上运行success
和error
API.doHttpRequest("POST", url, requestParams)
.success(function (data, status, headers, config) {
// successful data retrieval
console.log("request success");
console.log("state: "+status);
// do something with data
})
.error(function (data, status, headers, config) {
// do some stuff
});
这是我的小工作代码,它在$ http请求中使用promises
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope, dataService) {
dataService.then(function (data) {
$scope.data = data
})
});
app.controller('SecondCtrl', function($scope, dataService) {
dataService.then(function (data) {
$scope.secData = data
})
});
app.service('dataService', function ($http, $q){
var defferer = $q.defer()
$http.jsonp('http://ip.jsontest.com/?callback=JSON_CALLBACK').success(function (data){
defferer.resolve(data)
})
return defferer.promise
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.