我正在使用 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
实际上包含以下内容
url
= 当前状态的 url 例如。/user
templateUrl
= 模板的路径例如。path/to/something.html
controller
= 状态 ex 的 Controller 名称。usersController
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/