AngularJS只有两个HTTP GET请求返回时解决 [英] AngularJS return two http get requests only when resolved
问题描述
我有一个角的应用程序,并在控制器中我需要调用一个函数,这使得两个HTTP GET请求,我需要这个功能时,他们决定只返回这些值。因为这个功能需要在同一控制器所得到的值,我不能让他们在$ routeProvider决心。
I have an Angular app, and in the controller I need to call a function which makes two http get requests, and I need this function to return these values just when they are resolved. I cannot make them in the $routeProvider resolve because this function needs a value obtained in the same controller.
我显示控制器的一部分:
I show part of the controller:
function myController(info) {
var vm = this;
vm.name = info.data.name;
vm.extra_data = MyService.getExtras(name);
}
这是服务的code的一部分:
And here is part of the code of the service:
function myService($http, $q, API_EVENT1, API_EVENT2) {
return {
getExtras: getExtras
}
function getExtras(name) {
var request1 = API_EVENT1 + '/' + name;
var request2 = API_EVENT2 + '/' + name;
}
}
该功能是不完整的,由于我尝试了好几种方法,但我没有成功可言。
The function is not complete due to I have tried several methods, but I wasn't successful at all.
我的问题是如何返回(在getExtras功能)这两个请求的结果的。我一直在使用$ q.defer,$ q.all和承诺试过,但我不能去实现它。
My problem is how to return (in getExtras function) both of the results of the requests. I have tried using $q.defer, $q.all and promises, but I'm not able to achieve it.
使用$ q.all,比如我来检索结果,但是当我调用该函数,对象extra_data是不确定的,由于要求已经异步执行。
Using $q.all, for example, I got to retrieve the result, but when I call the function, the object extra_data is undefined, due to the requests have been executed asynchronously.
感谢您提前为您的答复。
Thank you in advance for your responses.
推荐答案
我会使用 $ q.all
返回来自服务相结合的承诺,并处理结果控制器。例如:
I would use $q.all
to return combined promise from Service, and process result in controller. e.g.:
function myService($http, $q, API_EVENT1, API_EVENT2) {
return {
getExtras: getExtras
}
function getExtras(name) {
return $q.all([
$http({method: 'GET', url: API_EVENT1 + '/' + name}),
$http({method: 'GET', url: API_EVENT2 + '/' + name})])
);
}
}
function myController(info) {
var vm = this;
vm.name = info.data.name;
MyService.getExtras(name).then(function(data) {
vm.extra_data.first = data[0];
vm.extra_data.second = data[1];
});
}
这篇关于AngularJS只有两个HTTP GET请求返回时解决的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!