I am working on a project based on ionic and angular js. I am loading JSON file which contains some JSON data in key-value pair. What I want to achieve is I have to call $urlRouterProvider.otherwise() method after json file is loaded completely. Following is the code which I have tried but it does not work for me. I have tried putting console in 'defaultRoute' function it is getting executed but '$urlRouterProvider.otherwise('/tab/myjobs')' this line doesn't work.The following code is present in app.config function. Any help will be appreciated.
$.getJSON('js/constants/'+lang+'.json')
.then(function(response) {
$translateProvider.translations(window.localStorage['deviceLanguage'],response);
defaultRoute($urlRouterProvider);
}, function(response) {
//$translate.use('en');
});
function defaultRoute($urlRouterProvider){
if(window.localStorage['userData']) {
var access_token = JSON.parse(window.localStorage['userData']).access_token;
if(access_token){
$urlRouterProvider.otherwise('/tab/myjobs');
}else{
$urlRouterProvider.otherwise('/login');
}
}else{
console.log("in line 282");
$urlRouterProvider.otherwise('/login');
}
}
The problem is that you are running an async method in the config phase.
AngularJS lifecycle is splitted in 2 phases, config (where you can use providers, but not services because these are not yet registered), and run (where you cannot use providers, but you can use services and in general is equivalent to the main function).
The run phase starts when config phase has finished, and config phase do not wait for any async process, so what is happening is that when your JSON get promise is solved your config phase has already finished (so any provider config you try to do in your promise success callback do not really config anything).
So in short, you cannot use $urlRouterProvider.otherwise() passing the result of an async call, like your getJson method.
A couple alternatives to what you are trying to do (redirect user depending on auth) are: angular ui-router login authentication and angularjs redirect to login page if not authenticated with exceptions.
Consider using
$state.go('someState')
You would want your code to look like this:
If you are trying to send the user to different routes conditionally, use
$state.go('route.path')
instead of updating the.otherwise()
configuration. For example: