Javascript 嵌套http.request AngularJS后同时显示数据
对于嵌套的多个http请求,我有一个问题:Javascript 嵌套http.request AngularJS后同时显示数据,javascript,angularjs,http,model-view-controller,Javascript,Angularjs,Http,Model View Controller,对于嵌套的多个http请求,我有一个问题: $http({ method: 'jsonp', url: 'URL1', }).then(function (response) { // Response result 1 // nested http request --> after first http success $http({ method: 'jsonp', url: 'URL2' }).th
$http({
method: 'jsonp',
url: 'URL1',
}).then(function (response) {
// Response result 1
// nested http request --> after first http success
$http({
method: 'jsonp',
url: 'URL2'
}).then(function (response) {
// Response result 2
}, function Error(response) {
$scope.users = response.statusText;
}).finally(function () {
$scope.loading = false;
});
});
};
有没有办法同时在视图上显示这两个结果?当我添加$scope.data.length
以确定在长度大于1时显示按钮时,按钮位于任何数据之前。我想在视图中同时显示来自这两个成功案例的数据。这可能吗
我已经读过关于$q
,但这在这里有效吗?在两个结果数据可用的同时渲染视图
PS:我知道在控制器中添加http
请求是不好的做法,但这只是为了测试。我建议使用承诺链接。还可以使用catch方法,这样可以提高代码的可读性
$http({ method: 'jsonp', url: 'URL1'})
.then(function (firstResult) {
//save firstResult
return $http({ method: 'jsonp', url: 'URL2'})
})
// this then will be called only if first one succeeds
.then(function (secondResult) {
//save secondResult - display data if this is available
})
.catch(function Error(response) {
// catch errors form both requests
$scope.users = response.statusText;
})
.finally(function () {
$scope.loading = false;
})
};
正如您所说,您必须像这样使用$q:
$q.all([$http({method:'jsonp',url:'URL1'})。$promise,$http({method:'jsonp',url:'URL2'})。$promise])。然后(callBackSuccess,callBackError);
函数callBackSuccess(结果){
var firstResult=结果[0];
//你想从firstResult得到什么
var secondResult=结果[1];
//你想从secondResult中得到什么
}