【发布时间】:2016-06-10 06:04:47
【问题描述】:
我正在尝试按如下方式使用 Promise...
$q.when().then(function () {
return $rootScope.$emit('resetView', false, 'default');
}).then(function (result) {
$log.info('login id loaded'); //execute this one first
checkUserlogin();
}).then(function (result) {
$log.info('Layout loaded'); //execute this one only when 1st is success. If 1st is failed, dont execute this one.
loadData();
}, function (error) {
$log.error("Caught an error:", error);
return $q.reject('New error');
});
如您所见,我有 2 个函数要执行。 checkUserLogin() 和 loadData()。
在 checkUserLogin() 中,我们检查是否允许用户访问。获取用户 ID 并通过 ajax 传递到后端。检查数据库。如果可以访问,则 loadData() 应该执行。如果访问不存在,则 loadData() 不应执行。
目前,这是正在发生的事情。 checkUserLogin() 被执行。用户 ID 通过 ajax 传递到后端。并直接执行 loadData()。现在一旦页面被加载,ajax 就会返回调用并知道用户没有访问权限。他被重定向到访问被拒绝的页面。
我不希望这种情况发生。页面加载应仅在确认用户具有访问权限后进行。知道如何实现吗?
编辑(根据下面 Paulpro 的回答)
$q.when().then(function () {
return $rootScope.$emit('resetView', false, 'default');
}).then(function (result) {
$log.info('checkuser loaded'); //execute this one first
return checkUserlogin();
}).then(function (result) {
$log.info('Layout loaded'); //execute this one only when 1st is success. If 1st is failed, dont execute this one.
return loadData();
}, function (error) {
$log.error("Caught an error:", error);
return $q.reject('New error');
});
var checkUserlogin = function() {
$log.info(' Inside Login check function executed');
var serviceURL_CheckUserExists = '/api//CheckUserExists';
//ajax to check if user exists in database. give/ deny access based on user present in DB and if user is set as blockuser in db.
$.ajax({
type: "GET",
url: serviceURL_CheckUserExists,
}).then(function (response) {
if (response.Results.length == 1 && response.Results[0].BlockUser == false) {
$rootScope.myLayout.eventHub.emit('getUserName', response.Results[0].User_ID.trim());
});
}
else { $window.location.href = '../../../BlockUser.html'; }
}
根据上述编辑 - 这是当前正在执行的步骤。 $log.info 给出如下输出。
checkuser loaded
Layout loaded
Inside Login check function executed
实际上,这些应该是步骤。
checkuser loaded
Inside Login check function executed
Layout loaded
【问题讨论】:
-
您能否粘贴
checkUserlogin的代码大纲,了解返回的内容和时间很重要。正如下面的答案所述,它假设它是一个新的承诺,但不可能从你的问题中知道。
标签: javascript jquery angularjs ajax promise