Dynamic header menu based on login data

hello the team!
I tried to look on the forum the solutions to the problem similar to this one but I still have not managed to correct it. please somebody can help me?

app.html

<ion-menu id="myMenu" [content]="content">

    <ion-header >
        <ion-navbar >
             <ion-title>   {{based on login data}}</ion-title>
       </ion-navbar>
    </ion-header>



</ion-menu>
      
<ion-nav id="nav" #content [root]="rootPage"></ion-nav>

app.component.ts


   logout() {
    this.auth.logout().subscribe(succ => {
    this.navCtrl.setRoot('LoginPage')
    });
  } 

  openPage(p){
    if(p.title == 'Profile'){
      this.navCtrl.push(p.page);
    }else{
        this.navCtrl.setRoot(p.page);
      }
    
  }

auth.service.ts

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import { BookingDataService } from '../booking-data-service/booking-data-service';


@Injectable()
export class User {
  name: string = "";
  email: string = "";
 
  constructor(name: string, email: string) {
    this.name = name;
    this.email = email;
  }
}

@Injectable()
export class AuthService {
  currentUser: User;

  constructor(private bds: BookingDataService) {
  }

  public login(credentials) {
    if (credentials.email === null || credentials.password === null) {
      return Observable.throw("Please insert credentials");
    } else {
      return Observable.create(observer => {
        // verifica password al backend
        //let access = (credentials.password === "pass" && credentials.email === "email");
        let access = (this.isPresentCredential(credentials.email));
        this.currentUser = new User('patrick', 'patrick.siyou@atos.com');
        observer.next(access);
        observer.complete();
      });
    }
  }

  isLoggedIn(){
    return this.currentUser != null;
  }

  

  public getUserEmail(){
    return this.currentUser.email;
  }
  
  
  public getUserPicture() : string {
    return "../assets/imgs/patrick.png";
  }
 
  public logout() {
    return Observable.create(observer => {
      this.currentUser = null;
      observer.next(true);
      observer.complete();
    });
  }

  getUserList(){
    return this.bds.getAllUserList();
  }

  isPresentCredential(email: string){
    let userList = this.getUserList();
    for(let i=0; i<userList.length; i++){
      if(userList[i].getEmail() == email){
        return true;
      }
    }
    return false;
  }

}

login.ts

import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams, AlertController, LoadingController, Loading, MenuController } from 'ionic-angular';
import { AuthService } from "../../providers/auth-service/auth-service";
import { HomePage } from "../home/home";


@IonicPage()
@Component({
  selector: 'page-login',
  templateUrl: 'login.html',
})

export class LoginPage {
  loading: Loading;
  registerCredentials = { email: '', password: '' };

  constructor(public nav: NavController, private auth: AuthService, private alertCtrl: AlertController, private loadingCtrl: LoadingController, public menuCtrl: MenuController) {
    //this.menuCtrl.enable(false, 'myMenu');
  }

 
  public login() {
    this.showLoading()
    this.auth.login(this.registerCredentials).subscribe(allowed => {
      if (allowed) {        
        this.nav.setRoot(HomePage);
      } else {
        this.showError("Access Denied");
      }
    },
      error => {
        this.showError(error);
      });
  }

  showLoading() {
    this.loading = this.loadingCtrl.create({
      content: 'Please wait...',
      dismissOnPageChange: true
    });
    this.loading.present();
  }
 
  showError(text) {
    this.loading.dismiss();
 
    let alert = this.alertCtrl.create({
      title: 'Fail',
      subTitle: text,
      buttons: ['OK']
    });
    alert.present();
  }

  ionViewDidEnter() {
    // the root left menu should be disabled on this page
    console.log("isLoggedIn: "+this.auth.isLoggedIn());
    this.menuCtrl.enable(false, 'myMenu');
  }

  ionViewWillLeave() {
    // enable the root left menu when leaving this page
    console.log("isLoggedIn: "+this.auth.isLoggedIn());
    this.menuCtrl.enable(true, 'myMenu');
  }

}

thank you

Perhaps I’m not sure what you mean by “login data”, but if you’re talking about what’s in AuthService.currentUser, can’t your app component simply inject AuthService and access it?

1 Like

I tried to do it but it does not work. I thought that since the app.html page loads before login.html, all login information will not be useful in app.html. I hope I’m wrong

What you could try doing is that when the app component initialize you may subscribe to an event from the AuthService you use to login. When you effectively login on your service, emit the event with the user data so your app component can listen and then load the information you may want to show on the header of your app.

on app.component.ts

 title: string;

constructor(private auth: AuthService){
     this.auth.loginChange.subscribe(
        (user) => {
              this.title = user.name;
         }
   );
}

on auth.service.ts

public user: User;
public loginChange: EventEmitter<User> = new EventEmitter();

public login(user: String, password: String): void {
    if(succesfullLogin){
        this.user = returnedUser;
        this.loginChange.next(this.user);
     }
}

I’d suggest you the following post on stackoverflow to understand better about event emitters, observables and subscriptions https://stackoverflow.com/questions/36076700/what-is-the-proper-use-of-an-eventemitter

1 Like