As a newbie to the Ionic Mobile Framework and Angular JS, I'm working on a login page for the first time. My goal is to navigate to the homepage only if the session has not expired when the login page launches. If the session has expired, then it should redirect back to the login page. The functionality works smoothly as I transition between the songs screen/state and the login screen/state. However, I'm facing an issue.
Upon app startup, it directly goes to the songs state or "home" page without executing the controller code for that state. In the controller code, I make a request to our website to check the active session status. If the session is still active, JSON data is returned; otherwise, my authInterceptor handles the transition to the login state.
The main problem lies in the fact that the controller doesn't run during app initialization, and despite extensive searching online, I haven't been able to identify the root cause. Below is a snippet of the code:
.run(function($ionicPlatform, $cordovaSplashscreen, localstorage, $state) {
setTimeout(function() {
$cordovaSplashscreen.hide()
}, 1500)
$ionicPlatform.ready(function() {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
if(window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
if(window.StatusBar) {
// org.apache.cordova.statusbar required
StatusBar.styleDefault();
}
if(localstorage.get('subdomain') == undefined ||
localstorage.get('subdomain') == 'null' ||
localstorage.get('subdomain') == null ||
localstorage.get('subdomain') == 'undefined' ||
localstorage.get('subdomain') == "")
{
$state.go('subdomain');
}
else
$state.go('songs');
});
})
.config(function($stateProvider, $urlRouterProvider, $httpProvider) {
$urlRouterProvider.otherwise("/songs");
$stateProvider
.state('login', {
url: "/login",
templateUrl: "templates/login.html",
controller: 'LoginCtrl'
})
.state('subdomain', {
url: "/subdomain",
templateUrl: "templates/subdomain.html",
controller: 'SubdomainCtrl'
})
.state('songs', {
url: "/songs",
templateUrl: "templates/songs.html",
controller: 'SongsCtrl'
})
$httpProvider.interceptors.push('authInterceptor');
});
// register the interceptor as a service
.factory('authInterceptor', function($q, $injector) {
return {
// optional method
'responseError': function(rejection) {
if(rejection.status == 0 || rejection.status == 403){
$injector.get('$state').transitionTo('login',null,{ reload: true, inherit: true, notify: true });
if(rejection.config.url.indexOf('login') > -1){
navigator.notification.alert("Invalid username or password.", function(){}, "Login Failed");
}
}
return $q.reject(rejection);
}
};
})
.controller('SongsCtrl', function($scope, $state, user) {
user.check(); //Resource that hits route on server
$scope.logout = function()
{
user.logout();
$state.go('login');
}
})
I appreciate your help. James