Angular UI router $transitions.onBefore

2020-07-11 06:41发布

I am using angular ui router version 1.0.0-alpha.4 and since by default root scope events are inactive I thought of using new way of implementing auth mechanism as follows.

.run(['$transitions', '$timeout', '$q', '$state', 'AuthService', ($transitions, $timeout, $q, $state, AuthService) => {
  $transitions.onBefore({ to: 'app.*', from: '*' }, () => {
    const deferred = $q.defer();
    AuthService.isLoggedIn().then(() => {
      deferred.resolve()
    }, () => {
      // redirect to error page 
      // how can i redirect user to error page. $state.go('error') not working. 
      deferred.reject()
    });
    return deferred.promise;
  }, {priority: 10});
}])

However issue is that I am not sure how to redirect user to error page. I try to use $state.go('error') and seems does not working. Any suggestions?

3条回答
\"骚年 ilove
2楼-- · 2020-07-11 07:07

Cool I found the solution. Posting this to anyone who may come up with the same issue. All you need is resolve the promise as follows.

deferred.resolve($state.target('error', undefined, { location: true }))
查看更多
【Aperson】
3楼-- · 2020-07-11 07:08

It could be even more simple because auth services also working with promise.

Just return the service and don't create another promise.

If you just interested in the negative case return the state in the catch phase.

.run(['$transitions', '$state', 'AuthService', ($transitions, $state, AuthService) => {
  $transitions.onBefore(
    { to: 'app.*', from: '*' },
    () => AuthService.isLoggedIn().catch(
        () => $state.target('error', undefined, { location: true })
    ),
    {priority: 10}
  );
}])
查看更多
Root(大扎)
4楼-- · 2020-07-11 07:13

To redirect the transition from a TransitionHook function you can return a TargetState or a promise that resolves a TargetState.

From the Ui-Router Docs

When returned from a TransitionHookFn or TransitionStateHookFn, these values alter the running Transition:
False: the transition will be cancelled.
TargetState: the transition will be redirected to the new target state.
Promise: the transition will wait for the promise to resolve or reject. (see below)

  • If the promise is rejected (or resolves to false), the transition will be cancelled
  • If the promise resolves to a TargetState, the transition will be redirected
  • If the promise resolves to anything else, the transition will resume

Anything else: the transition will resume

查看更多
登录 后发表回答