我想按照下面显示的顺序运行代码。但是,看起来整个函数在init函数之前运行。
因此,我收到以下错误:TypeError: Cannot set property 'total' of undefined
。
有关如何解决此问题的任何建议吗?
.controller('ProjectListCtrl', ['Auth', 'Projects', '$state', '$timeout', '$firebaseArray', 'Ref', function (Auth, Projects, $state, $timeout, $firebaseArray, Ref) {
var projectList = this;
// This code correctly runs first
if( Auth.$getAuth() === null ) {
Auth.$authAnonymously({rememberMe: true}).then(init)
.catch(function(error) {
console.log('error');
});
}
else {
init(Auth.$getAuth());
}
// This code runs last but should be second
function init(authData) {
projectList.projects = Projects(authData.uid);
}
// This code runs second but should be last
$timeout(function(){
projectList.projects.total = function () {
var total = 0;
angular.forEach(projectList.projects, function (project) {
if (project.type.govfee>0){total += (project.type.govfee+project.type.cost);}
else {
total += (project.type.cost);}
});
return total;
}; },200);
}]);
这是项目工厂:
.factory('Projects', ['$firebaseArray', 'FBURL', 'Auth', 'Ref', function($firebaseArray, FBURL, Auth, Ref) {
return function(uid) {
return $firebaseArray(Ref.child('projects').child(uid));
};
}]);
答案 0 :(得分:1)
将$ timeout包装的代码声明为函数,并从init函数调用它。这样可以保证通话顺序。
function init(authData) {
projectList.projects = Projects(authData.uid);
getTotals();
}
function getTotals(){
projectList.projects.total = function () {
var total = 0;
angular.forEach(projectList.projects, function (project) {
if (project.type.govfee>0){total += (project.type.govfee+project.type.cost);
} else {
total += (project.type.cost);
}
});
return total;
}
}
同样,如果Projects从异步操作返回一个promise,只需从promise解析中调用getTotals()
。
function init(authData) {
projectList.projects = Projects(authData.uid).then(function() {
getTotals();
});
}