Benjamin Li Benjamin Li - 1 year ago 75
AngularJS Question

angular how to prevent user typing url directly to access pages when he is logout

I am using

, so I have lots of states.

considering below scenario:
user is already logout, and he types url in the browser directly, like
, I should redirect it to the login page, which is

how to implement this? one of the methods is to check if the session is active in run block. is it a good practice to call backend API in the run block?

According to Ryan's suggestion, it calls backend api to check if user is logged in

$transitions.onBefore({to: 'home'}, function(transition) {
var $state = transition.router.stateService;
let promise = jsonService.heartBeat()
promise.then(data => {
if(!data.hasOwnProperty('data')) {
}, () => {

Answer Source

Levi's answer is correct for UI-Router pre-version 1.0. For UI-Router 1.0, the state change events such as $stateChangeStart are deprecated and this will no longer work. You can use the $transitions service instead.

function run ($transitions, Auth) {
  // 'to' param is the state name; 'main.**' will match 'main' and all sub-states
  $transitions.onBefore({to: 'main.**'}, function (transition) {
    var $state = transition.router.stateService;
    if (!Auth.isAuthenticated()) {

run.$inject = ['$transitions', 'Auth'];;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download