Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular UI Router 1.0.0 - prevent route load with $transitions.onBefore

I upgraded to UI Router 1.0.0, which has changed from .$on($stateChangeX to $transitions.onX( (see $transitions here).

I need to resolve the user's profile and their access BEFORE navigation to the page (e.g. the user should never see the page they're attempting to transition to). Before, I was able to use a resolve directly in the state and pass thru things I need sequentially, as such:

state('my-state', {
        ...
        resolve : {
            ProfileLoaded : ['$rootScope', function ($rootScope) {
                return $rootScope.loadProfile();
            }],
            access: ['Access', 'ProfileLoaded', function (Access, ProfileLoaded) {
                return Access.hasORRoles(['admin']); //either $q.reject(status code); or "200"
            }]
        }
    })

Then I could easily retrieve the error type in $stateChangeError:

app.run(...
    $rootScope.$on('$stateChangeError', function (event, toState, toParams, fromState, fromParams, error) {

       if (error === 401) {
           $state.go('home');
       }
       ...

With $transitions, I'm trying to do the same thing...

.state('user.my-page', {
  ...
  data: {
    loadProfile: true,
    roles: [
      'admin'
    ]
  }
});


app.run(...

  $transitions.onBefore({to: profile}, function(trans) {
    return loadProfile().then(function (prof) {
      var substate = trans.to();
      return Access.hasORRoles(substate.data.roles); //either $q.reject(status code); or "200"
    });
  });

  $transitions.onError({}, function(trans) {
    var error = trans && trans._error;

    if (error == 401) {
      $state.go('home');
    }
    ...

So my question is:

Does onBefore do the same thing as resolve in terms of ensuring the user can't navigate before data is checked? The page is still loading and THEN redirecting with $state.go after the page loads.

like image 309
user3871 Avatar asked Nov 09 '22 04:11

user3871


1 Answers

Just for people who are still landing here.

You can return a promisse to prevent the site from loading.

$transitions.onBefore({}, function(transition) {
      return new Promise((resolve) => { 
      // Do auth.. 
      return Access.hasORRoles(['admin']);
   });
});
like image 74
crani Avatar answered Nov 14 '22 21:11

crani