我是 Angular $q 服务的新手。我正在使用 $http
和 Angular $q
服务来实现异步请求。下面是我的代码,我无法获取后端 api 的结果。 (json)
Services.js:
.service('httpService', function($q, $http, $timeout) {
var asyncRequest = function(url) {
return $http.get(url)
.then(function(response) {
//res is the index of an array in php, which will be encoded.
return response.res;
}, function(response) {
// something went wrong
return $q.reject(response.res);
});
};
return {
asyncRequest : asyncRequest
};
});
Controller.js:
var result = httpService.test(url)
.then(function(data) {
// Line below gives me "undefined"
console.log(data);
}, function(error) {
alert("Error...!");
});
提到的行给了我未定义的信息。 (当然,我可以在主函数中编写console.log(data),但这不是一个好的做法,因为我想将结果返回给 Controller )
关于我的$q
服务的实现,有没有更简单的方法?
任何想法将不胜感激。
最佳答案
在这种情况下,您不应该不要使用$q
,因为$http
已经返回了一个promise。 2个一起使用效率低下。 (如果您使用非 Angular 异步函数(例如地理查找),$q
很有用)。
服务.js:
.service('httpService', function($http, $timeout) {
var asyncRequest = function(url) {
return $http.get(url)
};
return {
asyncRequest : asyncRequest
};
});
Controller .js:
var result = httpService.asyncRequest(url)
.then(function(res) {
console.log(res.data);
}, function(error) {
alert("Error...!");
});
关于javascript - AngularJS $http 结果与 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33984823/