I try to merge data from 2 webApis. Something like that:
我尝试合并来自2 webApis的数据。像这样的东西:
$http.get($scope.apiUrl1 + 'GetEmployees').success(function(data1) {
//process data1
$http.get($scope.apiUrl2 + 'GetEmployees2').success(function(data2) {
//process data2
var data = data1.join(data2);
})
})
What I don't like on this solution is because apiUrl2 is called after the response on first request.
我不喜欢这个解决方案是因为在第一次请求响应后调用了apiUrl2。
There is a way to call both api in the same time and to wait answer for both of them? Promise can be a solution?
有一种方法可以同时调用两个api并等待它们的答案吗?承诺可以解决方案吗?
2 个解决方案
#1
1
In angularJS you can use $q.all(), where each $http request is a variable, like so:
在angularJS中你可以使用$ q.all(),其中每个$ http请求都是一个变量,如下所示:
let get1 = $http.get($scope.apiUrl1 + 'GetEmployees');
let get2 = $http.get($scope.apiUrl2 + 'GetEmployees2');
$q.all([get1, get2]).then(data => {
console.log('the data: ', data);
});
//you can also pass in an object to $q.all, allowing you to refer to the promises by variable name rather than index
$q.all({get1, get2}).then(data => {
console.log('the data: ', data);
});
Here's a nice comprehensive blog about $q and what it can do:
这是一个很好的综合博客,关于$ q以及它可以做什么:
https://toddmotto.com/promises-angular-q
https://toddmotto.com/promises-angular-q
#2
3
use $q.all
. First Inject the $q
to the controller/
使用$ q.all。首先将$ q注入控制器/
let arr = [$http.get($scope.apiUrl1 + 'GetEmployees'), $http.get($scope.apiUrl2 + 'GetEmployees2')]
$q.all(arr).then(function (response) {
//process data2
var data = response[0].data.concat(response[1].data);
})
#1
1
In angularJS you can use $q.all(), where each $http request is a variable, like so:
在angularJS中你可以使用$ q.all(),其中每个$ http请求都是一个变量,如下所示:
let get1 = $http.get($scope.apiUrl1 + 'GetEmployees');
let get2 = $http.get($scope.apiUrl2 + 'GetEmployees2');
$q.all([get1, get2]).then(data => {
console.log('the data: ', data);
});
//you can also pass in an object to $q.all, allowing you to refer to the promises by variable name rather than index
$q.all({get1, get2}).then(data => {
console.log('the data: ', data);
});
Here's a nice comprehensive blog about $q and what it can do:
这是一个很好的综合博客,关于$ q以及它可以做什么:
https://toddmotto.com/promises-angular-q
https://toddmotto.com/promises-angular-q
#2
3
use $q.all
. First Inject the $q
to the controller/
使用$ q.all。首先将$ q注入控制器/
let arr = [$http.get($scope.apiUrl1 + 'GetEmployees'), $http.get($scope.apiUrl2 + 'GetEmployees2')]
$q.all(arr).then(function (response) {
//process data2
var data = response[0].data.concat(response[1].data);
})