Javascript sessionStorage登录变量的角度路由解析

Javascript sessionStorage登录变量的角度路由解析,javascript,angularjs,routes,resolve,Javascript,Angularjs,Routes,Resolve,我已经使用Angular JS构建了一个登录系统。用户登录时,将设置会话存储变量,并将其重定向到仪表板页面(应仅在登录时可访问)” 现在我想在需要用户登录的任何路由上使用resolve。我发现这方面的文档非常混乱,无法理解。如果用户未登录并试图访问其中一个页面,则需要向他们显示一条消息,说明他们无法访问该页面 app.config(function($routeProvider) { $routeProvider.when("/dashboard", { templateUrl :

我已经使用Angular JS构建了一个登录系统。用户登录时,将设置会话存储变量,并将其重定向到仪表板页面(应仅在登录时可访问)”

现在我想在需要用户登录的任何路由上使用resolve。我发现这方面的文档非常混乱,无法理解。如果用户未登录并试图访问其中一个页面,则需要向他们显示一条消息,说明他们无法访问该页面

app.config(function($routeProvider) {
  $routeProvider.when("/dashboard", {
    templateUrl : "framework/views/dashboard.html",
    controller  : "DashboardCtrl",
    title: "Dashboard",
    resolve: {
      //how does this work?!
    }
});


app.factory("loginCheckService", function(){
  //check sessionStorage and return?
});

您希望侦听locationChangeStart事件、执行验证(auth)、防止路由更改(如果需要)并引发一些事件(未授权)以显示登录表单

差不多

app.run(function($rootScope,LoginService){
      $rootScope.$on('$locationChangeStart',function(event){
          if(!LoginService.isUserLoggedIn()){
            event.preventDefault();
             //LoginService.raiseUserNotLoggedIn();  OR
                 $rootScope.$broadcast('UserNotLoggedIn');
         }

      });
  });

app.controller('LoginFormController',function($scope){
    $scope.userLoggedIn=true;
    $scope.on('UserNotLoggedIn',function(){
          $scope.userLoggedIn=false;
    });
});

Resolve允许您定义一组任务,这些任务将在加载路由之前执行。它只需要一组键和函数,就可以在页面加载之前执行异步http请求、运行代码段、设置值等操作(实际上,无论您想要什么)

因此,如果您有一个服务发出http get请求并返回一个承诺以确保每次路由发生时服务器上都存在会话,则resolve保证在http请求满足之前不会加载页面,并且该承诺是成功的。换句话说,如果满足的承诺失败,则页面将不会加载:

.config([ '$routeProvider', function( $routeProvide ) {

    $routeProvider.when('/dashboard', {
        templateUrl: 'framework/views/dashboard.html',
        controller: 'DashboardCtrl',
        controllerAs: 'dashCtrl',
        resolve: {
            DateOfBirth: ['Date', function( Date ) {  // random example of other uses for resolve
                return Date.getCurrentYear() - 37;
            }],
            AuthUser: ['$q', '$location', 'UserSession', 

                function( $q, $location, UserSession) {
                    return UserSession.getSession()

                    .then(function( success ) {  // server response 200 = OK
                       // if you are in here the promise has succeeded and 
                       // the page will load

                       // can do whatever you want

                       return success
                    }, function( error ) { // server response not 200 = Not OK

                       // if you are in here the promise has failed and 
                       // the page will not load

                       // can do whatever you want                         

                       // if unauthenticated typically you'd:
                       $location.path('/login);
                       $location.replace();

                       // for this read up on promises, but promises can be 
                       // chained, and it says move me to next error promise
                       // in the chain. if you don't use this it will assume
                       // the error was handled and pass you to the next 
                       // success in chain.  So good practice even if you're 
                       // not chaining
                       return $q.reject( error );
                    });
        }];
        }
    })
}]);
resolve的另一个优点是密钥是可注入的。因此,您可以将结果传递给控制器:

.controller('DashboardCtrl', ['AuthUser', 'UserSession', 'DateOfBirth' 
    function(AuthUser, UserSession, DateOfBirth) {

    // show all the errors you want by accessing the AuthUser 
    // data contained in the server response, or just read the 
    // server response status

    var self = this;

    self.status = AuthUser.status;
    self.response = AuthUser.data;
}]);
然后,在UI中,您可以使用dashCtrl.response或dashCtrl.status或您决定对解析数据执行的任何操作来显示或绑定结果,并在知道从未加载页面的情况下显示错误


我建议您在路由上检查会话,而不是将其存储在客户端。此外,请记住,解析仅在路由上有效,但如果您对不需要路由的服务器进行调用,则需要查看如何使用拦截器。拦截器允许您在与路由无关的传出和传入服务器请求/响应时达到峰值路由,所以当您当前在特定页面(如/dashboard/home)上时发生的那些不会触发路由,只需更新/home内容。

如果有什么不合理的地方,请告诉我
.controller('DashboardCtrl', ['AuthUser', 'UserSession', 'DateOfBirth' 
    function(AuthUser, UserSession, DateOfBirth) {

    // show all the errors you want by accessing the AuthUser 
    // data contained in the server response, or just read the 
    // server response status

    var self = this;

    self.status = AuthUser.status;
    self.response = AuthUser.data;
}]);