我试图在工厂内做出 promise ,然后在 locationChangeStart
中进行验证。问题是 locationChangeStart
没有等待我的 promise 。我该怎么做才能让我的 promise 等待完成?
这是我的代码,
app.run(['$rootScope','$location','KeyFactory',
function($root, $location,KeyFactory) {
$root.$on('$locationChangeStart', function(event, curr, prev) {
KeyFactory.check();
console.log(KeyFactory.GetKeyPass()); ///PRINT undefined
if(KeyFactory.GetKeyPass()== true){
console.log('authorised');
}else{
$location.path('/login');
}
});
}]);
app.factory('KeyFactory', ['$http','$log', function($http,$log) {
var key = {};
key.setKeyPass = function(set) {
key.Status = set;
}
key.GetKeyPass = function() {
return key.Status;
}
key.check = function(){
$http.post('http://localhost/api/CheckPass').success(function(data) {
console.log(data);
key.setKeyPass(true);
}).error(function (data, status){
$log.error("error you cant acess here!");
console.log(status);
});
}
return key;
}]);
最佳答案
异步代码并不像您想象的那样以同步方式工作。制作 ajax 后,它不会在下一行中响应。在创建 ajax 之后,在 Angular 中它返回一个 promise
对象,该对象负责告诉 response/error
将要发生。
您的代码中缺少一些东西。
- 您应该从服务的
check
方法返回一个 promise 。 - 然后将
.then
函数放在check
方法上,并在其成功/错误回调中期望响应。
代码
key.check = function(){
return $http.post('http://localhost/api/CheckPass').then(function(response) {
var data = response.data;
key.setKeyPass(true);
}, function (response){
key.setKeyPass(false);
});
运行
KeyFactory.check().then(function(){
if(KeyFactory.GetKeyPass()== true){
console.log('authorised');
}else{
$location.path('/login');
}
});
关于javascript - AngularJS 在加载路由之前解析 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41332723/