ionic2: how to automatically redirect to the login page

ionic2: how to automatically redirect to the login page

I got a point where it was important to implement an automatic redirection to the login page when the user tries to access a page that should be accessed from logged users only.

I needed something easy to add on every “reserved” page.
The first attempt was to create a service, I immediately faced with a problem:
The NavController (needed for the page change) can’t work form inside a service.

This is the error I got:
No provider for NavController

https://github.com/driftyco/ionic/issues/9581

I decided for a component.
The working principle is easy:

  1. When the app starts deletes the storage obj “user”
  2. Immediately after it tries to get a new obj from an api call by using the access token stored in the storage obj “session”
  3. If the call succeeds it saves the new storage obj “user”
  4. Every page that needs to be “protected” includes the component <login-redirect>
  5. <login-redirect> checks if the storage obj “user” exists, if it does not, it redirects to the login page passing a parameter used from the login component to redirect to a page(or back) if the login succeeds
  6. When the login succeeds, the login component calls the api again to fetch and set the storage obj “user”
  7. The login page redirects to the right page (passed as parameter on the point 5)

Let’s see some code:

I don’t need to modify the template or the scss file.

controller

The @Input() is used to read from the tag’s attribute “redirect” the page to pass to the login component (we’ll see it later)

The login component has some logic like this

In every page I want to reserve for logged users, I add this line in the template


This method works fine, anyway I don’t know yet if this is the best method to achieve the result, for example a little side effect is that the page we want to protect appears for a short time before the redirection.
As soon as I discover a better method I’ll share it.

Any suggestion?

Leave a Reply

Your email address will not be published. Required fields are marked *