我有 2 个全局变量:
$scope.genewtId = null;
$scope.data1 = null;
我有 2 个角函数,如下所示:
$scope.getID = function() {
Service1.getId("abc").then(function(response){
$scope.genewtId = response.data[0].Id;
console.log($scope.genewtId);
}, function(error){
console.log(error.statusText);
});
};
$scope.getDetails = function() {
Service2.getDetails($scope.genewtId).then(function(response){
// here response is having an error
$scope.data1 = response.data;
console.log($scope.data1.toString());
}, function(error){
console.log(error.statusText);
});
};
当我将$scope.genewtId
一个函数的值传递给另一个函数时,出现错误
消息:“未能将‘java.lang.String’类型的值转换为所需的类型‘java.lang.Integer’;嵌套异常是java.lang.NumberFormatException:对于输入字符串:“null””
但是,console.log($scope.genewtId);
正在返回一个值787651
,这意味着它不为空。
请建议是否可以使用 $rootScope.$broadcast
修改第一个函数以返回一个承诺:
$scope.getID = function() {
return Service1.getId("abc").then(function(response){
$scope.genewtId = response.data[0].Id;
console.log($scope.genewtId);
return response.data[0].Id;
}, function(error){
console.log(error.statusText);
throw error;
});
};
修改第二个函数以返回一个承诺并接受一个参数:
$scope.getDetails = function(id) {
var genewtID = id || $scope.genewtId;
return Service2.getDetails(genewtId).then(function(response){
$scope.data1 = response.data;
console.log($scope.data1.toString());
return response.data;
}, function(error){
console.log(error.statusText);
throw error;
});
};
然后链接两个承诺:
var promise = $scope.getId();
var promise2 = promise.then(function(id) {
return $scope.getDetails(id);
});
var promise2.then(function(data) {
console.log(data);
}).catch(function(error) {
console.log(error);
});
通过使用promise的.then
方法getId
,代码在id
向 发出请求之前等待值从服务器到达getDetails
。
因为调用.then
promise的方法会返回一个新的派生promise,所以很容易创建一个promise 链。可以创建任意长度的链,并且由于一个承诺可以用另一个承诺解决(这将进一步推迟其解决方案),因此可以在链中的任何点暂停/推迟承诺的解决。
有关更多信息,请参阅
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句