Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular UI router $transitions.onBefore

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?

like image 884
fernando Avatar asked May 01 '16 04:05

fernando


2 Answers

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 }))
like image 80
fernando Avatar answered Sep 18 '22 11:09

fernando


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}
  );
}])
like image 26
cstuncsik Avatar answered Sep 22 '22 11:09

cstuncsik