我的问题实际上与这里发现的问题非常相似:

AngularJs - cancel route change event

简而言之,我正在使用$ routeChangeStart并尝试使用$ location更改当前路由。完成后,控制台会显示原始页面仍在加载中,并很快被新页面覆盖。

提供的解决方案是使用$ locationChangeStart而不是$ routeChangeStart,这应该可以防止额外的重定向。不幸的是,我在更改路由时需要在$ routeprovider中使用其他数据(我用它来跟踪页面限制)。这是一个例子

$routeProvider.
    when('/login', { controller: 'LoginCtrl', templateUrl: '/app/partial/login.html', access: false}).
    when('/home', { controller: 'HomeCtrl', templateUrl: '/app/partial/home.html', access: true}).
    otherwise({ redirectTo: '/login' });


$rootScope.$on('$routeChangeStart', function(event, next, current) {
    if(next.access){
        //Do Stuff
    }
    else{
        $location.path("/login");
        //This will load the current route first (ie: '/home'), and then
        //redirect the user to the correct 'login' route.
    }
});

通过$ routeChangeStart,我可以将“next”和“current”参数(请参见AngularJS - $route)用作对象来检索“访问”值。使用$ locationChangeStart,这两个参数返回url字符串,而不是对象。因此,似乎没有办法检索我的“访问”值。

有什么方法可以结合使用$ locationChangeStart的重定向停止功能和$ routeChangeStart的对象灵活性来实现我所需要的?

最佳答案

我想到的一种方法是尝试为此使用resolve参数:

var resolver = function(access) {
  return {
    load: function($q) {
      if (access) { // fire $routeChangeSuccess
        var deferred = $q.defer();
        deferred.resolve();
        return deferred.promise;
      } else { // fire $routeChangeError
        return $q.reject("/login");
      }
    }
  }
}

$routeProvider.
  when('/login', { controller: 'LoginCtrl', templateUrl: '/app/partial/login.html', resolve: resolver(false)}).
  when('/home', { controller: 'HomeCtrl', templateUrl: '/app/partial/home.html', resolve: resolver(true)}).
  otherwise({ redirectTo: '/login' });

请注意,我没有测试上面的代码,但是我在项目中做类似的事情。

关于javascript - AngularJS-需要$ routeChangeStart和$ locationChangeStart的某种组合,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17978990/

10-11 06:47