Angular page redirect

I am creating an app where I wish to redirect a user directly to home page if he is logged in. I am using cordovaSQLite plugin to check if he is logged in or not. But I am not getting the value of cart_status. Is it because I am executing the query in angular.module ? I see that I can execute CREATE TABLE query in angular.module which stands a valid reason I should be able to execute some other query as well.

Here is my code

var db = null;
var ab= ""
angular.module('starter', ['ionic', 'starter.controllers', 'ionic-material', 'ionMdInput', 'ngCordova'])
.run(function($ionicPlatform, $cordovaSQLite) {
$ionicPlatform.ready(function() {
.
.
.
db = $cordovaSQLite.openDB({ name: "userdb", location: 0});
$cordovaSQLite.execute(db, "CREATE TABLE IF NOT EXISTS user_info (id integer primary key, firstname text, lastname text, user_id text, cart_id text, cart_status text, header_token text)");
var cart_query = "select cart_status from user_info LIMIT 1";
$cordovaSQLite.execute(db, cart_query, [])
.then(function(suc){
ab = suc.rows.item(0).cart_status
},
function(uerr){
alert(JSON.stringify(uerr))
})
});
})

And here

.config(function($stateProvider, $urlRouterProvider, $ionicConfigProvider) {
.
.
.
alert(ab) // which is blank 
})

yeah… sqlite is executed async… Everywhere you are using callbacks or promises it is an indicator of possible asyc execution of code-blocks.

Even the “platform.ready” call is async.

But angular does not know that and can run the config block before your code is event executed. and in other cases… And you should totally read something about basic javascript and angular… never use global variables to share code between parts of a homepage, angular app… never ever do it.

1 Like

So how am I suppose to redirect a user as app opens to login page or home page based upon the value in sqlite database?

set login router as default route --> and use ui.routers resolves to check if the use is logged in before routing --> if not redirect to logged in page.

As you mentioned I was not following the right approach by declaring global variables so now I am eager to know if creating a default page and then redirecting accordingly is considered the right way? Regards