.run在$ http回调之前启动。 Angular ui-router

时间:2017-08-03 05:56:06

标签: javascript angularjs routing angular-ui-router transition

我正在使用ui-router 1.0.0.X,它的转换是新的标准 我的代码:

  • 登录服务,保存存储中的数据,确定是否存在并清除

    app.factory('AuthService', ['$http', '$cookies', '$rootScope',
    function ($http, $cookies, $rootScope) {
    
        var service = {};
    
        // Authenticates throug a rest service
        service.authenticate = function (email, password, callback) {
    
            $http.post('endPoints/login.php', {
                    email: email,
                    password: password
                })
                .then(function (response) {
    
                    callback(response);        
                });
        };
    
        // Creates a cookie and set the Authorization header
        service.setCredentials = function (response) {
    
            $rootScope.globals = response;
    
            $http.defaults.headers.common['Authorization'] = 'Bearer ' + response;
            $cookies.put('globals', $rootScope.globals);
        };
    
        // Checks if it's authenticated
        service.isAuthenticated = function () {
    
            console.log("If TRUE callback not worked yet!!",$cookies.get('globals') === undefined);
    
            return !($cookies.get('globals') === undefined);
        };
    
        // Clear credentials when logout
        service.clearCredentials = function () {
            $rootScope.globals = undefined;
            $cookies.remove('globals');
                          console.log("CLEAN coockies globals",$cookies.get('globals'));
    
            $http.defaults.headers.common.Authorization = 'Bearer ';
        };
    
        return service;
    }
    ]);
    
  • 配置并运行。我们有转换方法可以工作:

    angular.module('myApp', 
    ['ui.router',
    'ngCookies'
    ])
    .config(['$stateProvider', '$urlRouterProvider',
        function ($stateProvider, $urlRouterProvider) {
            $urlRouterProvider.otherwise('/resumen');
            $stateProvider
                    .state("dashboard", {
                        url: "/dashboard",
                        templateUrl: "partials/dashboard.html",
                        controller: "dashCtrl",
                        data: {
                            authRequired: true
                        }
                    })
                    .state("login", {
                        url: "/login",
                        templateUrl: "partials/login.html",
                        controller: "loginController"
                    })
        }])
    
    .run(['$rootScope', '$transitions', '$state', '$cookies', '$http', 'AuthService',
        function ($rootScope, $transitions, $state, $cookies, $http, AuthService) {
    
            // keep user logged in after page refresh
            $rootScope.globals = $cookies.get('globals') || {};
            $http.defaults.headers.common['Authorization'] = 'Bearer ' + $rootScope.globals;
    
            $transitions.onStart({
                to: function (state) {
                    return state.data != null && state.data.authRequired === true;
                }
            }, function () {
            console.log("I'm transition.onStart and i'm alive!!!");
                if (!AuthService.isAuthenticated()) {
                    return $state.target("autorize");
                }
            });
        }]);
    

在仪表板状态下,我使用数据标记只有经过身份验证才可访问的状态。 然后,在.run上,我使用过渡来检查验证状态。

  • 我的控制器。 $ scope.logIn绑定到ng-click指令:

        $scope.logIn = function () {
        AuthService.authenticate($scope.loginInfo.email, $scope.loginInfo.password, function (callback) { 
    
        console.log("CALLBACK!",callback); //-> callback from server. Always true
    
        AuthService.setCredentials(callback);   
    });
    

    }

所有这些都按预期工作,但在首先 ng-click我接收到: enter image description here

所以,带有转换的.run方法在从服务器点击回调之前运行。

第二次 ng-click数据已在之前的ng-click服务器请求中设置,因此一切正常! enter image description here

所以,问题是如何避免那些可怕的两次点击呼叫。

$ transition的文档,其中我参与了部分代码: http://angular-ui.github.io/ui-router/1.0.0-alpha.1/interfaces/transition.ihookregistry.html

相关帖子:angular ui-router login authentication

0 个答案:

没有答案