2
votes

I am creating a app in ionic2. I am facing an issue that on successful login in the app, if I refresh the page it again forces me to login screen but it should not as I have been logged in.

I have used Ionic 2 with menus as a kick start.

Steps I did:

  1. Set root page as Loginpage insteed of Page1 which one was default in app.component.ts file.

    rootPage: any = Loginpage;

  2. On clicking submit redirect to newly created homepage.ts as:

    this.navCtrl.push(Homepage,{});

  3. In homepage.ts, I set my root page as any of one page say page2 as:

    this.navCtrl.setRoot(Page2);

    • Now on successful login I am redirected to Page2 correctly but if I reload the page at this time it again pushes me back to login page (but I am already logged in).

    • So the question is that how to overcome this issue?

    • What is the better approach for login authentication in ionic2.

2
are you doing this in phone/emulator? and how are you checking if loggedin - Suraj Rao
basically i am testing it in chrome browser itself not app installed in phone. I am using login api created with PHP laravell framework and on its success i am redirecting it to homepage. - Narendra Vyas
Can you please suggest is the way i am using correct or their is another way used in ionic2. I mean is there a module which is used to perform this or we do as i did in a custom way ... ?? this is my main doubt. - Narendra Vyas
you are basically using ionic serve on browser. It will reload the whole app. You will have to test in emulator/phone for this. - Suraj Rao
ok thanks @Suraj i will do the same . Thanks for replying. Can you please tell me if this way is correct or i shall go with a different approach thanks again. - Narendra Vyas

2 Answers

1
votes

you are basically using ionic serve on browser. It will reload the whole app. You will have to test in emulator/phone for this.

Regarding the approach you have in the question:

After login you should set root as home page instead of push.

this.navCtrl.setRoot(Homepage,{});

and push the other pages later.

this.navCtrl.push(Page2);

to maintain the navigation stack. Check the Navcontroller here.

1
votes
  • you can store Flag in local-storage, If you get this flag than redirect to Your Homepage or login page
  • Write below code in your app.component.ts

 import { Platform, App } from 'ionic-angular';

 constructor(public platform  : Platform,
             public app       : App )
        {
          platform.ready().then(() => {
               if(localStorage.getItem('appToken'))
                   this.app.getRootNav().setRoot(TabsPage);
               else
                  this.app.getRootNav().setRoot(LoginPage);
          });
       }