Javascript 在工厂加载必要设置之前调用工厂函数
我有一个工厂。下面的代码将立即加载设置和设置变量: AuthService.js:Javascript 在工厂加载必要设置之前调用工厂函数,javascript,angularjs,angular-ui-router,bluebird,Javascript,Angularjs,Angular Ui Router,Bluebird,我有一个工厂。下面的代码将立即加载设置和设置变量: AuthService.js: SettingService.loadSettings().then(function(config){ console.log('loading settings') settings = config; expirationDate = moment(settings.trialEndDate); remainingDays = expirationDate.diff(mo
SettingService.loadSettings().then(function(config){
console.log('loading settings')
settings = config;
expirationDate = moment(settings.trialEndDate);
remainingDays = expirationDate.diff(moment(),'days');
isExpired = remainingDays <= 0 ? true : false;
});
AuthService.js>hasAccess():
问题:用于检查我的许可证是否有效的我的函数(
hasAccess()
)正在工厂加载设置和过期状态之前运行<代码>设置正在返回未定义
。是否可以继续调用hasAccess()
,直到settings
不再是未定义的?hasAccess()
如果使用else
条件,则不会返回任何内容。由于licenseValidCheck()
返回承诺。。。。对于这两个条件,您可能需要从hasAccess()
返回一个承诺。更简单的方法可能是在路由中使用resolve
config@charlietfl您是否在谈论如何将返回结果的范围限定到then函数?我想我可以通过将result
的值设置为该范围之外的变量来解决这个问题。这是一个很好的捕获,但我不认为它解决了我的设置在调用hasAccess
之前没有准备好的问题。另外,从我所看到的,解析是在我的路由提供程序的状态上设置的,当我可以在状态更改时使用事件处理程序进行检查时,将此检查添加到每个状态似乎不是很枯燥。是的,我需要将整个hasAccess
功能转化为承诺。我更新了OP。
$rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams) {
AuthService.hasAccess().then(function(result){
console.log('access result',result)
if ( (hasAccess == false) && toState.name !== "settings") {
event.preventDefault();
toastr.warning('Your trial has expired');
$state.go('settings');
}else{
console.log("License is valid or trial not expired.");
}
});
});
function hasAccess() {
var d = $q.defer();
// test if they have license
console.log('Check if license present');
if (_.isNull(settings.organization.license)){
// No License
// Return trial status
d.resolve(isExpired);
}else{
// There IS a license
// Validate license
licenseCheck().then(function(licenseResult) {
d.resolve(licenseResult);
})
}
return d.promise
}