javascript - 在 Angular 中使用 ngroute 重定向未经授权的用户

标签 javascript angularjs ngroute

我正在使用 Angular 作为前端制作一个网络应用程序。 如果 Angular 色为教师的用户尝试访问申请人的门户,我想通过显示 404.html 模板来阻止他们。我不想将用户重定向到 www.example.com/404 ,而是让他们留在 www.example.com/teacher 的位置,但进行渲染404.html 模板。

我不确定如何使用 ngroute 来实现这一点。这是我在 app.js 中的代码:

app.config(['$routeProvider', '$locationProvider', 'CookieProvider',
    function ($routeProvider, $locationProvider, CookieProvider) {
            var cookieData = CookieProvider.$get().getCookieData();

$routeProvider.when('/applicant', {
            templateUrl: '/front-end/public/views/Prescreening/review.html',
            controller: 'ReviewCtrl',
            resolve:{
                "check":function($location, CookieService) {
                            var cookieData = CookieService.get();
                            if(cookieData["user_role"] == 'teacher'){
                                $location.path('/404')
                            }
                }
            }
        }).when('/404', {
            templateUrl: '/404.html'
        }).otherwise({
            templateUrl: '/404.html'
  });
  }]);

如何在不将用户重定向到 /404 的情况下呈现 404.thml?

最佳答案

假设您有这样的状态。

.state('dashboard.users', {
    url: '/users/:isAdmin',
    templateUrl: 'modules/dashboard/templates/users.html',
    controller: 'usersController',
})

试试这个。

angular.module(...)
    .config( ['$routeProvider', function($routeProvider) {...}] )
    .run(function($rootScope, $location) {
        $rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams){
            // You can pass the user role to the params 
            // of the state and you will see that on the 
            // toParams call callback ex. {isAdmin:false}
            if(!toParams.isAmin){
                toState.templateUrl = "modules/404/templates/404.html";
            }
        });
    })
})

更新

回调toState实际上包含以下内容

  1. url = 当前状态的 url 例如。 /user

  2. templateUrl = 模板的路径例如。 path/to/something.html

  3. controller = 状态 ex 的 Controller 名称。 usersController

  4. name = 州名 ex. dashboard.user

当执行此行时toState.templateUrl = "modules/404/templates/404.html";您所在州的当前模板属于 <div ui-view></div>将有404.html你想要的。

重要

您必须使用ui.router而不是ngRouter使这个实现工作有效。

关于javascript - 在 Angular 中使用 ngroute 重定向未经授权的用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37825056/

相关文章:

javascript - "Controller"未注册 angularjs

javascript - React - 将 `this` 绑定(bind)到导入的函数

Javascript随机颜色生成器,但偏爱浓烈的颜色

javascript - jQuery attr() 方法创建数据破折号属性

javascript - 如何将 Geodjango 与 Google Maps API 3 集成?

javascript - angularjs orderBy 无法正常工作

javascript - AngularJS 服务不返回 promise

angularjs - 为什么 Controller 不能与 ng-src 一起使用?

javascript - AngularJS,$routeProvider

angularjs - ng-view的“Controller as”语法