JS: Conditionally Interrupting navigation to a certain page and redirect to another (login)

nativescriptcore

#1

Hi, I’m adding a login screen to my application but instead of making it the “home”, initial page, I’m planning it to be launched based on a global flag indicating if the user is logged in or not.

The code below would be in every page that needs validation. It’s working, indeed BUT I get to see a bit of the actual page, before being redirected to the login page.

The thing is that it seems that onNavigatingTo happens when the page has ALREADY being rendered. Is there some other event that I can trap before that process happens? Any other tip for javascript is welcome. Thanks!

// THIS THE PAGE BEING VERIFIED (only should be shown if the user is logged in)
function onNavigatingTo(args) {
    const page = args.object;

    if (global.loggedIn == false) {
        frameModule.topmost().navigate({
            moduleName: "pages/login/login-page",
            transition: {
                name: "fade"
            }
        });
    }        

    page.bindingContext = new ReportsViewModel();
}

#2

Why don’t you simply use a global function to navigate, write your logic to cancel navigation there. For example,

ui-helper.js

// Assume these 2 pages listed below needs login
var requiresLogin = ["pages/home/home-page", "pages/settings/settings-page"];
exports.navigate = function(args) {
  
   // If not logged in and trying to navigate to the page that requires login, then redirect to login
   if (global.loggedIn == false && requiresLogin.indexOf(args.moduleName) >= 0) {
        frameModule.topmost().navigate({
            moduleName: "pages/login/login-page",
            transition: {
                name: "fade"
            }
        });
      return false;
   }

  // Continue to actual page otherwise
  frameModule.topmost().navigate(args);
};

Whenever you want to navigate

var uiHelper = require('~/ui-helper')
...
uiHelper.navigate(params)

#3

Thanks this is brilliant!! For now I had resorted to intervene the sidedrawer launcher, but this is a much more elegant solution, and also can re use it when I need to launch a page from outside the drawer.

This is pure coding, but I’m still lacking the skill/security to start thinking up such solutions. This is really great, thanks again.