简体   繁体   中英

Make AngularJS Transition cleaner without preloading

I remember reading a guide on how to make sure angular doesn't preload the {{ }} and other various bits before the final render for a few milliseconds, but I can't dig it up.

Can anyone point me in the right direction?

You can use $stateChangeStart event of ui-route to check whether user try to go to a state which requires authentication. You need to listen to that event during run phase of your app, you can check the following.

angular.module("yourApp").run(function($rootScope, $state){
    $rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams){
         if(toState === "yourStateWhichRequiresAuthentication" && authenticationFailed){
         event.preventDefault();
         $state.go("loginState");

} }) });

Even better you can add data to your states and define which states need authentication and check whether toState needs authentication using that data value as the following:

//Data Definition in your state definition
$stateProvider
  .state("main", {
    url: "main",
    template: "<div>Main State</div>",
    data: {needsAuthentication: true})

if (toState.data && toState.data.needsAuthentication) {
   if (!$rootScope.isAuthenticated()) { // user is not logged in
      event.preventDefault();
      $state.go("login");
   }
}

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