Javascript .run在$http回调之前启动。角度用户界面路由器
我正在使用ui路由器1.0.0.X及其新标准。Javascript .run在$http回调之前启动。角度用户界面路由器,javascript,angularjs,routing,angular-ui-router,transition,Javascript,Angularjs,Routing,Angular Ui Router,Transition,我正在使用ui路由器1.0.0.X及其新标准。 我的代码: 用于登录的服务,将数据保存在存储器中,确定它是否存在并清除 app.factory('AuthService', ['$http', '$cookies', '$rootScope', function ($http, $cookies, $rootScope) { var service = {}; // Authenticates throug a rest service service.authen
我的代码:
- 用于登录的服务,将数据保存在存储器中,确定它是否存在并清除
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"); } }); }]);
- 我的控制器$绑定到ng click指令的scope.logIn:
}$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); });