Search code examples
angularionic-frameworkionic5

How to pass storage (User session) data to side menu ionic 5?


i am new in ionic and started from youtube tutorials , i created a crud in ionic using PHP, my sql in success login i redirect to home page and by using home.page.ts i can get storage data in home.page.html, but i am not able to pass user storage data in side menu to show user name in side menu, i tried in app. component. ts to get storage data and pass to side menu which html is in app. component. html but its not showing on first login but after login when i refresh it shows name that's because it is added storage else condition in app. component. ts i even added that method in after ready but still no luck i need help on this pls.

app.component.ts


import { Platform } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';

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

@Component({
  selector: 'app-root',
  templateUrl: 'app.component.html',
  styleUrls: ['app.component.scss']
})
export class AppComponent {

  datastorage: any;
  patient_name: string;
  patient_no: string;

  constructor(
    private platform: Platform,
    private splashScreen: SplashScreen,
    private statusBar: StatusBar,
    private storage: Storage,
    public navCtrl: NavController
  ) {
    this.initializeApp();
  }

  initializeApp() {
    this.platform.ready().then(() => {
      this.statusBar.styleDefault();
      this.splashScreen.hide();
      
       this.storage.get('storage_xxx').then((res)=>{
             if(res==null)
             {
               this.navCtrl.navigateRoot('/login');
             }
             else
             {
               console.log(res);
              this.datastorage=res;
              this.patient_name = this.datastorage.patient_name;
              this.patient_no = this.datastorage.patient_no;
              this.navCtrl.navigateRoot('/home');
             }
        });
      
    });

   this.storage.get('storage_xxx').then((res)=>{
     if(res==null)
     {
       this.navCtrl.navigateRoot('/login');
     }
     else
     {
       console.log(res);
      this.datastorage=res;
      this.patient_name = this.datastorage.patient_name;
      this.patient_no = this.datastorage.patient_no;
      this.navCtrl.navigateRoot('/home');
     }
   });

  }
}

app.component.html

<ion-app>
  <ion-menu menuId="main-menu" contentId="main">
    <ion-content>
     <div class="menu-header-bg"></div>
     <div class="header-content">
       <img src="../assets/images/avatar.jpeg" alt="">
       <ion-label>
         <h2>{{patient_name}}</h2>
         <p>Num: {{patient_no}}</p>
       </ion-label>
     </div>
     <div class="action-button">
       <ion-button>
          <ion-icon slot="start" name="add"></ion-icon>Add Branch
        </ion-button>
     </div>
     <ion-list lines="none" class="menu-items">
      <ion-item>
        <ion-icon name="home"></ion-icon> Dashboard
      </ion-item>
       <ion-item>
         <ion-icon name="browsers-outline"></ion-icon> Post Session
       </ion-item>
       <ion-item class="active">
        <ion-icon name="flash"></ion-icon> Live Session
      </ion-item>
      <ion-item>
        <ion-icon name="heart-outline"></ion-icon> Library
      </ion-item>
      <ion-item>
        <ion-icon name="chatbubble-ellipses-outline"></ion-icon> Message
      </ion-item>
      <ion-item>
        <ion-icon name="exit-outline"></ion-icon> Sign Out
      </ion-item>
     </ion-list>
    </ion-content>
  </ion-menu>
  <ion-router-outlet id="main"></ion-router-outlet>
</ion-app>

login.page.ts

import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { ToastController, LoadingController, AlertController, NavController } from '@ionic/angular';
import { AccessProviders } from '../../providers/access-providers';
import { Storage } from '@ionic/storage';
import { resolve } from 'dns';
import { promise } from 'protractor';

@Component({
  selector: 'app-login',
  templateUrl: './login.page.html',
  styleUrls: ['./login.page.scss'],
})
export class LoginPage implements OnInit {

  user_login_name: string="";
  login_password: string="";

  disabledButton;

  constructor(
    private router : Router,
    private toastCtrl : ToastController,
    private loadingCtrl : LoadingController,
    private alertCtrl : AlertController,
    private accessPrvds : AccessProviders,
    private storage: Storage,
    public navCtrl: NavController
  ) { }

  ngOnInit() {
  }

  ionViewDidEnter()
  {
    this.disabledButton=false;
  }

  openRegister()
  {
    this.router.navigate(['/register']);
  }

  async tryLogin()
  {
   if(this.user_login_name==""){
      this.presentToast("Username is required");
    }
    else if(this.login_password==""){
      this.presentToast("Password is required");
    }
    else{
      this.disabledButton=true;
      const loader = await this.loadingCtrl.create({
        message:"Please wait...",
      });
      loader.present();

      return new Promise(resolve=>{

        let body = {
          aksi : "process_login",
          user_login_name: this.user_login_name,
          login_password: this.login_password,
        }

        this.accessPrvds.postData(body, 'process_api.php').subscribe((res:any) => {
            if(res.success==true)
            {
              //console.log(res.result);
              loader.dismiss();
              this.disabledButton=false;
              this.presentToast('Login successfull');
              this.storage.set('storage_xxx',res.result); // store session data
              this.navCtrl.navigateRoot(['/home']);
            }
            else
            {
              loader.dismiss();
              this.disabledButton=false;
              this.presentToast('Username or password is wrong');
            }
        }, (err)=>{
              loader.dismiss();
              this.disabledButton=false;
              this.presentToast('Timeout!');
        });

      });

    }
  }

  async presentToast(a)
  {
    const toast = await this.toastCtrl.create({
      message:a,
      duration:1500
    });
    toast.present();
  }

  async presentLoader(a)
  {
    const loader = await this.loadingCtrl.create({
      message:"Please wait...",
    });
    loader.present();
  }

  async presentAlert(a) {
    const alert = await this.alertCtrl.create({
      header: a,
      backdropDismiss: false,
      buttons: [
        {
          text: 'Close',
          handler: (blah) => {
            console.log('Confirm Cancel: blah');
          }
        }, {
          text: 'Try Again',
          handler: () => {
            this.tryLogin();
          }
        }
      ]
    });

    await alert.present();
  }

}



Solution

  • Try this

    Create the AuthService service

    import {Injectable} from '@angular/core';
    import {BehaviorSubject} from 'rxjs';
    
    
    @Injectable({
        providedIn: 'root'
    })
    export class AuthService {
    
        private loggedIn = new BehaviorSubject<boolean>(false);
    
        constructor(private storage: Storage) {
        }
    
        get isLoggedIn() {
            return this.loggedIn.asObservable();
        }
    
        public setLogged(user) {
            if (!!user) {
                this.storage.set('storage_xxx',user); // store session data
                this.loggedIn.next(true);
            }
        }
    
        logout() {
            this.loggedIn.next(false);
        }
    }
    

    Import AuthService into LoginPage

    constructor(
        private router : Router,
        private toastCtrl : ToastController,
        private loadingCtrl : LoadingController,
        private alertCtrl : AlertController,
        private accessPrvds : AccessProviders,
        private storage: Storage,
        private authService: AuthService,
        public navCtrl: NavController
      ) { }
    

    And change the code of the tryLogin method

    this.storage.set('storage_xxx',res.result); // store session data
    

    To

    this.authService.setLogged(res.result); // store session data
    

    Include the code in the AppComponent

    export class AppComponent { 
        private isLoggedIn$: Observable<boolean>;
        ...
    
    constructor(
        private platform: Platform,
        private splashScreen: SplashScreen,
        private statusBar: StatusBar,
        private storage: Storage,
        public navCtrl: NavController
      ) {
        this.isLoggedIn$ = this.authService.isLoggedIn;
        this.initializeApp();
        this.checkLogin();
      }
    
    private checkLogin() {
        this.isLoggedIn$.subscribe(value => {
            if (value) {
                this.storage.get('storage_xxx').then((res)=>{
                    if (res !== null) {
                        this.datastorage=res;
                        this.patient_name = this.datastorage.patient_name;
                        this.patient_no = this.datastorage.patient_no;
                        this.navCtrl.navigateRoot('/home');
                    }
                }); 
            } else {
                this.patient_name = "";
                this.patient_no = "";
            }
        });
    }