AngularJS - Need some combination of $routeChangeStart and $locationChangeStart

后端 未结 4 1755
夕颜
夕颜 2020-12-23 10:46

My problem is actually very similar to the one found here:

AngularJs - cancel route change event

In short, I\'m using $routeChangeStart and trying to change

4条回答
  •  遥遥无期
    2020-12-23 10:59

    Nice answer Marius, put me on the right track. I'm doing something like this for access control. This works however...

      var resolver = function(route, routeEvent) {
      return {
        load: function($q) {
          deferred = $q.defer();
          if (routeEvent!=3) { // eventually will be a list of routeEvents that the logged-in user is not allowed to visit read from a db table configured by admin
            deferred = $q.defer();
            deferred.resolve();
            return deferred.promise;
          } else { // fire $routeChangeError
            alert("You don't have permissions to access this.");
            deferred.reject(route);
            return deferred.promise;
          }
        }
      }
    }
    
      var jsonRoutes = [
    
        {'route' : '/logout', 'templateUrl': 'partials/login.html',   'controller' : 'LoginCtrl', 'routeEvent' : 1 },
        {'route' : '/orders', 'templateUrl': 'partials/orders.html',   'controller': 'OrderListCtrl', 'routeEvent' : 2 },
        {'route' : '/products', 'templateUrl': 'partials/products.html',   'controller': 'ProductListCtrl', 'routeEvent' : 3 },
    
    ...
    
    ];
    
    
    // somewhere on successful login code add in the dynamic routes
    
    angular.forEach(jsonRoutes, function(r) {
                    $route.routes[r.route] = {templateUrl: r.templateUrl, controller: r.controller, routeEvent: r.routeEvent, resolve: resolver(r.route, r.routeEvent)};
                      });
    
    
    // got some static routes too which don't have access control - user has to login right?
    
      config(['$routeProvider', function($routeProvider) {
    
    
      $routeProvider.
        when('/error',  {templateUrl: 'partials/error.html',   controller : ErrorCtrl,  routeEvent : 1 }).
        when('/login',  {templateUrl: 'partials/login.html',   controller : LoginCtrl, routeEvent : 1 }).
        when('/home',  {templateUrl: 'partials/home.html',   controller : HomeCtrl, routeEvent : 1 }).
        when('/logout', {templateUrl: 'partials/login.html',   controller : LoginCtrl, routeEvent : 1 }).
        otherwise( {redirectTo: '/error'} );   
    

    When the /orders route is clicked the promise is rejected (with a pop-up, could be modal dialog) and the route isn't followed.

    Hope this helps someone.

提交回复
热议问题