简体   繁体   中英

Angular get route parameters from location change start

I have routes setup like so:

app.config(function($routeProvider) {

  $routeProvider

  //login
  .when("/", {
    templateUrl : "framework/views/login.html",
    controller  : "LoginCtrl",
    title: "Login",
    authenticate: false
  })

  //dashboard
 .when("/dashboard", {
    templateUrl : "framework/views/dashboard.html",
    controller  : "DashboardCtrl",
    title: "Dashboard",
    authenticate: true
  });
});

Now I want to redirect location changes if authenticate is set to true on the route but a session variable is not true .

For example:

$rootScope.$on("$locationChangeStart", function(event, newURL, oldURL){ 
  if (toState.authenticate && $window.sessionStorage.isLoggedIn) {
    $location.path("/");
  }
});

This works if I use $routeChangeStart instead, but then I see the next route briefly before it redirects. Location change seems to stop that, but I can't work out how to access the route parameters (ie the authenticate parameter).

How do I do this? Or is there a better way entirely?

you should use the resolve parameter within the .when(). This acts as a promise where you can set certain criteria that must be satisfied before the view is rendered. You can find a good demo video here: https://egghead.io/lessons/angularjs-resolve

As I stated in the comment and on demand of Cooper I post an example:

angular.module('myApp',[])
    .factory('httpInterceptor', ['$q', '$location',function ($q, $location) {
        var canceller = $q.defer();
        return {
            'request': function(config) {
                // promise that should abort the request when resolved.
                config.timeout = canceller.promise;
                return config;
            },
            'response': function(response) {
                return response;
            },
            'responseError': function(rejection) {
                if (rejection.status === 401) {
                    canceller.resolve('Unauthorized'); 
                    $location.url('/user/signin');
                }
                if (rejection.status === 403) {
                    canceller.resolve('Forbidden');  
                    $location.url('/');
                }
                return $q.reject(rejection);
            }

        };
    }
    ])
    //Http Intercpetor to check auth failures for xhr requests
   .config(['$httpProvider',function($httpProvider) {
        $httpProvider.interceptors.push('httpInterceptor');
    }])
    .config(['$stateProvider',function($stateProvider) {

        // states for users
        $stateProvider
        .state('users', {
            abstract: true,
            templateUrl: 'users/views/users.html',
            resolve: {
                issessionedin: function(Sessions){
                    return Sessions.isLoggedIn();
                } 
            }
        })
        .state('users.account', {
            url: '/user/account/:id',
            templateUrl: 'users/views/account.html',
            resolve: {
                user: function(Users, $stateParams){
                    return Users.get($stateParams.id);
                }
            },
            controller:'UserAccountController'
        })
    }])
    .factory('Sessions', ['$http',
        function($http) {
            return{
                isSessionedIn :function() {
                    $http.get('/api/v1/issessionedin');
                },
                isLoggedIn :function() {
                    $http.get('/api/v1/isloggedin');
                },
                hasAccess :function(permission) {
                    $http.get('/api/v1/hasaccess/'+permission);
                }
            };
        }
    ]);

of course you need the code server side to return the http status code

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM