javascript - AngularJS 在加载路由之前解析 promise

标签 javascript angularjs

我试图在工厂内做出 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 将要发生。

您的代码中缺少一些东西。

  1. 您应该从服务的 check 方法返回一个 promise 。
  2. 然后将 .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/

相关文章:

javascript - 使用其值查找某个复选框

javascript - 从字符串中删除最后一个字符实例 - Javascript - 重访

javascript - 强制加载图像以停止闪烁?

angularjs - 从模板( View )中动态加载 AngularJS 模块

angularjs - 如何使用 ngResource 处理 3 级深度嵌套资源?

javascript - 简单验证也不起作用

javascript - 如何在javascript中获取频率值?

javascript - 使用 AngularJS 在书写页面中进行预览

javascript - AngularJS ng-repeat 不重复,没有控制台错误

angularjs - 依赖性破坏了应用程序