Best way to check login globally in Ionic 2

Greetings gals and guys. I’m trying to figure out the best way to globally check for authenticated user. Here’s my app.js and auth provider files. Looking for help/feedback on best way to do this:

app.js

import 'es6-shim';
import {App, Platform} from 'ionic-angular';
import {StatusBar} from 'ionic-native';
import {Page1} from './pages/page1/page1';
import {LoginPage} from './pages/login/login';
import {AuthService} from './providers/auth-service/auth-service';


@App({
  template: '<ion-nav [root]="rootPage"></ion-nav>',
  config: {},
  providers: [AuthService]
})
export class MyApp {
  static get parameters() {
return [[Platform], [AuthService]];
}

constructor(platform, auth) {

 if( !auth.login() ){
     this.rootPage = LoginPage;
 } else {
     this.rootPage = Page1;
}

platform.ready().then(() => {
  StatusBar.styleDefault();
});
  }
}

auth-service.js

import 'es6-shim';
import {App, Platform} from 'ionic-angular';
import {StatusBar} from 'ionic-native';
import {Page1} from './pages/page1/page1';
import {LoginPage} from './pages/login/login'; 
import {AuthService} from './providers/auth-service/auth-service';


@App({
  template: '<ion-nav [root]="rootPage"></ion-nav>',
  config: {},
  providers: [AuthService]
})
export class MyApp {
  static get parameters() {
    return [[Platform], [AuthService]];
  }

 constructor(platform, auth) {

 if( !auth.login() ){
     this.rootPage = LoginPage;
 } else {
     this.rootPage = Page1;
}

platform.ready().then(() => {
  StatusBar.styleDefault();
});
}
}

can you be more specific? What you have above is checking globally…

In most cases like this, logging in and out is something that can happen multiple times, triggered by different events. Treating it like something that can be dealt with only at startup in the application constructor is probably going to cause a fair amount of frustration and pain.

How about having an observable in your AuthService that tells anybody who is interested when a login or logout event has happened?

Personally, I also defer all this logic to an application root page that never changes. That page is responsible for deciding whether to navigate to login or register or the logged-in main application stack.

globally, meaning no matter what page you are on, the app will validate your login

Another answer here in the forum that I will quote the Ionic 2 Conference Application.

Take a look at how it works with this.loggedIn and the listenToLoginEvents() function to check changes with this.events.subscribe

https://github.com/driftyco/ has a very wide range of examples and starters to learn.

3 Likes