I am using angular UI router with my app which has html5 routing (angular's html5 mode) enabled.
I navigate from one state to another mostly using ui-sref and it works fine. However, at times when I use the browser back button, nothing happens. Please note, this is a one of event. When it does work though, when I try going "forward" with my browser controls, nothing happens and I remain on the same state. All my states have unique urls. I am sort of stuck with this issue and unable to proceed. Any pointers would be helpful.
This is the way I set my application base path:
<base href="/" target="_blank">
This is what my router setup looks like:
$stateProvider
.state("base",{
abstract: true,
url: "/app",
template: "<div ui-view></div>"
})
.state("login", {
url: "/login",
parent: "base",
templateUrl: "somePath",
controller: "loginController"
})
.state("auth",{
abstract: true,
parent: "base"
resolve: {
user: function(StateService){
return StateService.getCurrentUser();
}
}
})
.state("state1", {
url: "/state1",
parent: "auth",
templateUrl: "somePath",
controller: "state1Controller"
})
.state("state2", {
url: "/state2",
parent: "auth",
templateUrl: "somePath",
controller: "state2Controller"
});
I essentially have some base state where I resolve some things and add a base path to rest of my sub states. I then have another abstract state where I resolve my current user. It has many child states, each can only be accessed by a logged in user.
The StateService
has a function getCurrentUser
that makes a request to get details of the current user from my backend. My backend maintains a session which has the details of the current user. If there is no user in the session, it returns a 401. To this, I redirect my user to the login page. If not, I just continue and the UI router takes care of the rest. For now, let us assume I don't store this user on a cookie, so if the page is refreshed, the request goes again to my backend.
I have a few interceptors as well. They listen to the $stateChangeStart
event for some other application logic. For example, if the user is already logged in and he/she tries to go to the login page, I stop the state change and redirect the user to some default state (lets say state1). These are registered in the run block of my app.
$rootScope.$on("$stateChangeStart", function(event, toState, toParams, fromState) {
if(toState && toState.url =="/login"){
StateService.getCurrentUser()
.then(function(user){
$state.go("state1")
})
.catch(function(){
// no problem, go ahead
});
}
});
At this point I am not sure what else code to provide, let me know if anything else is required. I think there could be some problem with the way state changes are stored in the browser history. If that can happen, please let me know how so that I can figure our what part of my code is causing it.