如何在angularjs中使用第一个api的结果,进入第二个api调用
How to use result of first api, into second api call in angularjs?
我想将第一个api的结果用于第二个api调用。场景是这样的,我想使用第一个api的结果,进入第二个api调用。如果我是正确的,那么我想要同步api调用(不确定)。我试着写下面的函数,但没有成功。function2在function1之前调用在函数2中,我们使用result1,它只有在函数2之前调用函数1时才出现,我该怎么做。
$scope.function1 = function(){
var deferred= $q.defer();
$http.post(api1, data1)
.success(function(response, status) {
if (response.error == 0) {
console.log(response.result);
$scope.result1=response.result;
}
}) ;
deferred.resolve('Success') ;
return deferred.promise;
};
var promise = $scope.addDefaultValue();
promise.then(function(){
$scope.function2();
});
$scope.function2=function(){
var deferred = $q.defer();
$http.post(api2,result1)
.success(function(response, status){
if(response.error == 0){
}
});
deferred.resolve('Success') ;
return deferred.promise;
}
您可以在这里遵循promise链模式,在promise对象上使用.then
进行链接。
无需使用$q
创建额外开销的promise,因为$http
方法在启动ajax时返回promise对象。
代码
$scope.function1 = function() {
return $http.post(api1, data1)
.then(function(d) {
var response = d.data;
if (response.error == 0) {
console.log(response.result);
$scope.result1 = response.result;
}
return response;
});
};
$scope.function1().then(function(data) {
$scope.function2();
}, function(error) {
});
不能将$http
请求转换为"同步"请求。这不是"延期"的作用。Deferred是一种将不具有promise功能的函数转换为具有promise能力的函数的方法。$http
函数返回promise对象,因此不需要使用deferred。
$http.post(api, data1).then(function (response) {
$scope.result1 = response.data.result;
// return is important here
// so that you can keep chaining with .then
return $http.post(api2, response.data.result);
}).then(function (response) {
// here you have response from api2
$scope.result2 = response.data.result;
console.log(response.data);
}).catch(function (error) {
// here you can handle errors
// from either api calls
// second api call won't be made if the first one fails
console.log(error);
});
相关文章:
- jQuery使用api获取typeform结果
- 从JSON API结果迭代时未定义
- 与网络界面相比,谷歌搜索API有时会重复第一个结果,有时会重复第二个结果
- 从语音识别api结果中删除以前识别的单词
- 如何从autocomplete.getPlace()获取Google Place api结果
- 向 API 结果添加数据
- 如何将谷歌放置 API 结果数组与淘汰赛集成
- 无法在 MVC 中使用 jquery/js 将 json 数据(API 结果)绑定到下拉列表
- 显示牛津项目的情感 API 结果
- 按关键字过滤 Google 地点 API 结果
- 谷歌地图Javascript API-结果格式
- NodeJS ExpressJS如何打印API结果数组
- 如何制作一个显示必应翻译API结果的简单网页
- 从API结果中下载图像
- 限制Google Places Api结果
- 谷歌地图API -结果.几何.Location[0]返回null
- 使用请求获取API结果,并集成到Hubot响应中
- 运行并显示keydown事件的api结果
- 将卡片样式应用于单个Google Feed API结果
- 从 Google 云端硬盘 API 结果中排除特定的 mimeType