角路由的基本解决方案

驯鹿代码

我正在使用Angular JS创建一个非常基本的登录系统。基本上,提交登录表单后,将使用PHP和Mysqli针对数据库检查凭据。如果一切正常,则返回成功,$rootScope.isLoggedIn = true然后在其他类似变量中设置类似和用户详细信息的变量。

现在,我正在尝试找出resolve与路线一起使用的最佳方法,以便只有登录的用户或具有正确权限的用户才能访问页面(包括重新加载页面!)

我只是无法理解这些解决方案的工作方式。到目前为止,我的路由看起来像这样(仪表板页面需要用户登录):

app.config(function($routeProvider) {

  $routeProvider

  //login
  .when('/', {
    templateUrl : 'framework/views/login.html',
    controller  : 'LoginCtrl',
    title: 'Admin Login'
  })

  //dashboard
  .when('/dashboard', {
    templateUrl : 'framework/views/dashboard.html',
    controller  : 'DashboardCtrl',
    title: 'Dashboard',
    resolve: { ? }
  })

  //catch all redirect
  .otherwise({ redirectTo: '/' });

 });
醋甲酸酯

Resolve会在获得价值后立即(立即或在返回的诺言得到解决时)使用已解析的变量(可以注入到控制器中)打开您的路线。看:

resolve: { 
    myVar: function(service, $rootScope, etc){
        return service.obj; // or primitive, or promise or something else
    }
}
.controller('DashboardCtrl', function(myVar){
    console.log(myVar); // that service.obj goes here
}

这不能阻止路由加载(据我了解,如果我输入错误,请更正我)。

对于您的情况,最好使用如下所示的内容:

.when('/', {
    templateUrl : 'framework/views/login.html',
    controller  : 'LoginCtrl',
    title: 'Admin Login',
    authenticate: false
})
.when('/dashboard', {
    templateUrl : 'framework/views/dashboard.html',
    controller  : 'DashboardCtrl',
    title: 'Dashboard',
    authenticate: true
})

$rootScope.$on("$routeChangeStart", function(event, toState){
    if (toState.authenticate && !$rootScope.isLoggedIn){
        $location.path('/');
    }
});

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章