调用服务后,我的变量没有任何值。我将成功函数定义为一个单独的函数,并在.then()
方法中调用它,这里是代码:
// Code inside the Ctrl:
var successData = null;
vm.fillVar = null;
vm.loadData = loadData;
// service func
function loadData() {
return $timeout(function () {
vm.fillVar = vm.fillVar || [];
if (vm.fillVar == undefined || vm.fillVar.length == 0) {
CrudSvc.GetAllData().$promise.then(success, error);
console.log('Success Variable: ', successData); //--> here, the successData variable contains no data
vm.fillVar = successData;
console.log('fillVar for the view: ', vm.fillVar); //--> fillVar is empty, why??
}
}, 500);
}
// success func
function success(res) {
console.log('var res: ', res); //--> res contains data
successData = res;
console.log('success func: ', successData); //--> the variable contains data
}
在调用success函数后,我不明白为什么successData变量为空。这有点令人困惑......有没有人能解决这个问题呢?
答案 0 :(得分:3)
此代码为异步CrudSvc.GetAllData().$promise.then(success, error).then(function(){
// this code is executed after all the previous code is done and succeed
console.log('Success Variable: ', successData);
vm.fillVar = successData;
console.log('fillVar for the view: ', vm.fillVar);
});
,因此如果您想在此之后执行某些操作,则应将代码更改为:
then
您可以阅读reject
链接HERE
then方法返回一个允许方法链接的Promise。
修改强>
如果您想处理错误情况,只需使用CrudSvc.GetAllData().$promise.then(success, error).then(function(){
// this code is executed if previous success
}, function(){
// this code is executed if previous error
}); // This is how you do further error handling via this approach
函数,如下所示:
{{1}}
答案 1 :(得分:0)
// Code inside the Ctrl:
var successData = null;
vm.fillVar = null;
vm.loadData = loadData;
// service func
function loadData() {
return $timeout(function () {
vm.fillVar = vm.fillVar || [];
if (vm.fillVar == undefined || vm.fillVar.length == 0) {
CrudSvc.GetAllData().$promise.then(function(response) {
successData = response;
console.log('Success Variable: ', successData); //--> here, the success variable now contains no data
vm.fillVar = successData;
console.log('fillVar for the view: ', vm.fillVar); //--> fillVar is empty, why??
}, function(error) {
});
}
}, 500);
}