0
votes

I am using UI Router in Angular 2 for rout

UIRouterModule.forRoot({ 
  states: APP_STATES, 
  useHash: true,
  config: routerConfigFn,
  otherwise: { state: 'home' }
})

The home state requires auth:

export const homeState = {
  parent: 'app',
  name: 'home',
  url: '/home',
  component: HomeComponent,
  data: {requiresAuth: true}
};

Because it requires auth, I redirect to login page using the example here: https://github.com/ui-router/sample-app-angular/blob/master/src/app/global/auth.hook.ts

export function requiresAuthHook(transitionService: TransitionService) {
  const requiresAuthCriteria = {
    to: (state) => state.data && state.data.requiresAuth
  };

  const redirectToLogin = (transition) => {
    const authService: AuthService = transition.injector().get(AuthService);

    const $state = transition.router.stateService;
    if (!authService.isAuthenticated()) {
       return $state.target('login', undefined, { location: false });
    }
  };

  transitionService.onBefore(requiresAuthCriteria, redirectToLogin, {priority: 10});
}

But when I launch the app, it enters into an infinite loop. My login state does not require auth, $state.target('login) still runs requiresAuthHook.

1
try to use /login instead 'login' I think is because is trying to access /home/loginRicardo
Tried that, didn't work. $state.target() takes the name of the state rather than the path, so 'login' should be the right way to do itjCoder

1 Answers

0
votes

It's been a while since I asked this question, but I was able to finally solve this. Instead of using onBefore hook, I am now using onStart. I'm not entirely sure why this solves the problem, since onBefore comes before onStart in the lifecycle.

Anyway, switching to onStart did solve the problem.

Note:: in $state.target, remove {location: false} otherwise the URL is not updated on redirect. So, it should be: $state.target('login', undefined, {}); or simply, $state.targe('login');