kxyz
kxyz

Reputation: 842

Redirect in $transition.onBefore in ui-router

I'm using angular with components and ui-router 1.0.0-beta.3. This version doesn't send events related to change state, there are hooks. Before each state change I want to revalidate if user is authenticated and if has required roles. In case if not I want to redirect him to login page.

$transitions.onBefore({}, $transition => {

        const $toState = $transition.$to();

        if ($toState.data && $toState.data.authentication) {

            PrincipalService.identity().then(() => {
                return true;
            }, () => {
                console.log('redirecting');
                let $state = $transition.router.stateService;

                // not works
                //return $state.target('home');
                //return $transition.router.stateService.t('login');
            });
        } else {
            return Promise.resolve(false);
        }
    });

How to make this working ? With these cases I'm getting error about break the transition.

I based on official documentation

Upvotes: 4

Views: 6181

Answers (3)

harishr
harishr

Reputation: 18055

below worked for me

  $transition.abort();
  state.go('abcd')

Upvotes: 1

Syiwa Wahyu Saputra
Syiwa Wahyu Saputra

Reputation: 121

Use target from stateService inside your condition.

return $transition.router.stateService.target('login');

You can see it at Migration Example 3 (https://ui-router.github.io/guide/ng1/migrate-to-1_0#state-change-events)

Upvotes: 5

kxyz
kxyz

Reputation: 842

Solution:

Use transitionTo(stateName); and return true to stop current transition.

$transition.router.stateService.transitionTo(stateName);
return true;

Upvotes: 4

Related Questions