Switch initial page depending on value in SqlStorage


#1

I have an app where people have to login. When they do a token is set in SqlStorage.

Currently I have my App class defined as:

class MyApp {

    rootPage: any = Timelines;

In the Timeline class I have a check for the token. If it is not present the user is redirected to the login page. Is there a nicer way to achieve this behaviour? I especially like it when the token check login is in the app class.

One problem could be that retrieving the token from SqlStorage is async.


#2

“Nicer” is really subjective. What concrete problem are you having? Why do you like having this logic in the app class?


#3

With my current solution the user sees the timeline for a brief moment. Then it goes back to the login page which is not very nice behaviour from UI perspective. Besides the timeline already tries to load the timeline data, bug since the token is not there it gets a server error.

Switching between the login and timeline at app level solves these problems. Of course I am open for any other solutions.


#4

OK. What I do in this situation is to have a DispatchPage which is set as the app root page. It has an empty template, and contains the logic to decide whether to go to the login page or the timeline page, injecting NavController and calling its setRoot.


#5

That is exactly what I thought yesterday so I build it like:

constructor(private nav: NavController, private navParams: NavParams, private storage: StorageService) {

// Works
if (true) {
  console.log('Timelines');
  nav.setRoot(Timelines);
} else {
  console.log('login');
  nav.setRoot(Login);
}

// Doesn't work
storage.get('account.token').subscribe(token => {

  if (!null) {
    console.log('Timelines');
    nav.setRoot(Timelines);
  } else {
    console.log('login');
    nav.setRoot(Login);
  }

});

}

The weird thing is that in an Observable setting the root doesn’t always work. The Timelines page is a tabbed page. Although I see the ‘Timelines’ message in my console. The page does not navigate to it. If I send it to login there is no problem.

Outside the Observable there is no problem at all. If I maken the statement true of false it redirects correctly.


#6

Perhaps related to this issue.