0

I made simple app with Ionic 3/ Angular 5. Just Login and Home page. User is hardcoded (mocked) in AuthService. After login, I do this.nav.push('HomePage') where nav is NavController in loginPage.ts file.

In authService I have this:

return Observable.create(observer => {
  let access = (credentials.password === "pw" && credentials.email === "em");
  this.currentUser = new User('Test', 'test@mail.com');
  observer.next(access);
  observer.complete();
});

and:

public getUserInfo(): User {
  return this.currentUser;
}

In homePage.ts I have this (auth is authService injected into component):

constructor(private nav: NavController, private auth: AuthService) {
  let info = this.auth.getUserInfo();
  this.username = info['name'];
  this.email = info['email'];
}

After login, my app is on Home page. And if I reload Home page, user gets lost, and this.auth.getUserInfo() returns null...

What is best practice to keep user data (token etc.) in application lifetime and to check if user exists on desired page, if no user, return to login and clear all cache etc, and if user exists, reload that page or do whatever?

Walter Luszczyk
  • 1,369
  • 2
  • 19
  • 36

1 Answers1

0

Here is the some basic local storage examples,

Local Storage Reference Link:-

Local storage in Angular 2

    localStorage.setItem("user", "Muthu");
    // localStorage.setItem("user", JSON.stringify("Muthu")); also do like this while object.

    let userName=localStorage.getItem("user");

   //let userName = JSON.parse(localStorage.getItem("user")); if you set some object using stringify method. then you can use like this,

    if(userName!=null && userName!=undefined){ 
       this.nav.push('HomePage'); //do some stuff for valid user
    }else{
       this.nav.push('LoginPage'); //do some stuff for invalid user
    }

Local Storage Clear Reference Link:-

Clearing localStorage in javascript?

Clear All,

localStorage.clear();

Clear specific one,

localStorage.removeItem("user");

You don't need this localStorage let's try storage in ionic

Reference Link:-

https://ionicframework.com/docs/storage/

Install:-

ionic cordova plugin add cordova-sqlite-storage
npm install --save @ionic/storage

import app.module.ts file

import { IonicStorageModule } from '@ionic/storage';

 imports: [   
    IonicStorageModule.forRoot()
  ],

Typescript File,

import { Storage } from '@ionic/storage';

  constructor(private storage: Storage) { }

 // set a key/value
  storage.set('name', 'Max');

  // Or to get a key/value pair
  storage.get('name').then((val) => {
    console.log('Your name is', val);
  });

My best reference is simply use localStorage. I hope it's solve your problem.

Karnan Muthukumar
  • 1,843
  • 1
  • 8
  • 15