AngularJS $ http结果与承诺 [英] AngularJS $http result with promise
问题描述
我是angular $ q服务的新手.我正在使用$http
和angular $q
服务来实现异步请求.下面是我的代码,我无法获取后端api的结果. (json)
I am new in angular $q service.I'm using $http
with angular $q
service for implementing asynchronous requests. Here in below is my codes which I can't get the result of backend 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...!");
});
提到的那行,给我未定义. (当然,我可以在main函数中编写console.log(data),但这不是一个好习惯,因为我想将结果返回给控制器)
The mentioned line, gives me undefined. (Of course, I can write console.log(data) in main function, But it's not a good practice, because I want to return result to controller)
关于我的$q
服务的实现,有没有更简单的方法?
About my implementation of $q
service, is there any easier way?
任何想法都将不胜感激.
Any idea would be greatly appreciated.
推荐答案
在这种情况下,您不要使用$q
,因为$http
已经返回了诺言.将2一起使用效率低下. (如果您使用的是非角度异步功能,例如地理查询,则使用$q
.
You should not use $q
in this instance, as $http
already returns a promise. Using to 2 together in inefficient. ($q
is of use if you are using a non-angular async function, such as a Geo lookup).
Services.js:
Services.js :
.service('httpService', function($http, $timeout) {
var asyncRequest = function(url) {
return $http.get(url)
};
return {
asyncRequest : asyncRequest
};
});
Controller.js:
Controller.js :
var result = httpService.asyncRequest(url)
.then(function(res) {
console.log(res.data);
}, function(error) {
alert("Error...!");
});
这篇关于AngularJS $ http结果与承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!