Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 320
kxyz Avatar asked Dec 25 '22 00:12

kxyz


1 Answers

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)

like image 184
Syiwa Wahyu Saputra Avatar answered Jan 02 '23 02:01

Syiwa Wahyu Saputra