I am working on a Angular + Meteor project with the ui-router.
My issues is that when people are logged in and manually go to the /login route, I want to redirect them directly to the home page.
I don't want to do this in the controller but directly in the route. I tried onEnter function, but that doesn't have the $meteor dependency at hand to see if the user is logged in.
So then I got to resolve (https://github.com/angular-ui/ui-router/wiki#resolve).
With this I created a working solution, however it feels partly like a hack and I would love some feedback or suggestions on how to remove the hacky part.
The route Code (in coffeescript):
.state( 'public.login',
url: '/login'
views:
"container@public":
templateUrl: 'client/views/session/login.html'
controller: 'SessionCtrl'
resolve:
'currentUser': [ '$meteor', '$state', ( $meteor, $state )->
$meteor.waitForUser().then( ( user )->
if user
$state.go( 'private.home' )
, ( error ) ->
console.log("error", error)
)
return
]
)
As you can see that instead of passing on the promise as return of the resolve function, I check the promise myself and if user is logged in, I do a state change back to Home.
This works, but it feels like I am hacking the resolve function.
I don' want to add a listenter to the `stateChangeError' as situated in the example 8.5 @ http://angular-meteor.com/tutorials/angular1/user-accounts-authentication-and-permissions. There they catch the error if the resolve promise is false, in my case I do the opposite and only want to relocate when the promise is true.
Any suggestions?
***update**** Added this solution based on suggestion by Nikhil. Thanks for this!
angular.module( 'myApp' ).run(
( $rootScope, $location, $state ) ->
$rootScope.$on( '$stateChangeStart', ( event, toState, toParams, fromState, fromParams ) ->
if toState.name is 'public.login'
if event and event.targetScope and event.targetScope.currentUser
#to prevent login view to be displayed, I prevent default
event.preventDefault();
$state.go( 'private.home' )
)
)