$ rootScope事件不工作Angularjs

时间:2016-05-25 05:01:01

标签: javascript angularjs

我已在 myApp.run 下声明 $ rootScope。$ on 功能,以检查每个经过身份验证的页面中的令牌值。但它无法正常工作。我不明白为什么它不起作用。请帮助我。

app.js

myApp.run(['$rootScope','$state', '$location', 'loginService', function ($rootScope,$state, $location, loginService) {

    console.log(" under run => ");
    $rootScope.$on('routeChangeStart', function (event, next, current) {
        /*If route is authenticated then check if the user has access token, else return to login screen*/

        console.log(event);

        if (next.$$route.authenticated) {

            var userAuth = loginService.getUserToken();
            console.log(" usertoken => " +userAuth);
            if (!userAuth) {
                $location.path("/");
            }
        }

    });
 }]);

代码打印在控制台“under run =>”但是它没有打印事件对象,也没有检查是否有条件。

2 个答案:

答案 0 :(得分:2)

照顾 $

$rootScope.$on('$stateChangeStart',...)

答案 1 :(得分:0)

angular.module('...')..config( ['$routeProvider', function($routeProvider) {...}] )..run( function($rootScope, $location) {
// register listener to watch route changes
$rootScope.$on( "$routeChangeStart", function(event, next, current) {
  if ( $rootScope.loggedUser == null ) {
    // no logged user, we should be going to #login
    if ( next.templateUrl == "partials/login.html" ) {
      // already going to #login, no redirect needed
    } else {
      // not going to #login, we should redirect now
      $location.path( "/login" );
    }
  }         
});

有一点似乎很奇怪,我必须测试部分名称(login.html),因为" next" Route对象没有url或其他东西。也许有更好的方法吗?