How to update sidemenu?

How do I make the menu update the data depending on the page where I am? Since the menus are static in components, when I click on the menu is updated. But that is not something functional because I need a usability to display the data when I first open the menu, below code if I update data but the menu does not notice the changes … thanks to help me here

I see no code, but can you use the conference app as a starting point? It has the capability of making dynamic menus.

App.html
< ion-menu (click)=“actualizarnombre()” [content]=“content” id=“menuEstudiante”>
< ion-header>
< /ion-header>
< ion-content>
< img class=“perfil” src=“assets/img/felipe.jpg”>
< div class=“spacer”>
< div class=“itmprofile”>
< h5 text-center >{{name}}
< p text-center>{{rol}}


< /div >
< /ion-content>
< ion-footer>
< button menuClose ion-item (click)=“logout()”>
< ion-icon name=“power” item-left>
Cerrar sesión
< /ion-footer>
< /ion-menu>
Components.ts
public actualizarnombre(){
NativeStorage.getItem(‘user’).then(
data=>{
console.log("data ",data);
this.rol = data.rol;
this.name = data.name;
this.email = data.email;

}, (error)=>{
console.log(error);
});

}
Update name is the function that brings the data of native, in my login I update them, but the side menu does not take the data automatically, but if when clicking on any part of the menu if it is updated, I try from my login instances Myapp Again, and effectively change the values ​​of the variables, but the ion-menu is still not updated, with {{name}} and {{ rol}} connected to the changes you just updated

Login.Ts
this.navCtrl.setRoot(MyApp);

In general what I want to do is show the name and role in the menu, I manage three menus for different roles, but the data I get in the login, and the component is only launched at the beginning of the app ? I think it’s been clear

The (click) handler of the menu seems to be just about the worst possible place to be calling actualizarnombre() from. Can’t you call actualizarnombre() from somewhere else (like the constructor or a lifecycle event such as ngOnChanges if user is coming in via an input property binding)? That should allow change detection to work naturally.

If you absolutely insist on calling it from that click handler, you are probably going to have to inject a ChangeDetectorRef and manually goose change detection.

I already did both, as I said in the constructor also called the function and print the data and if indeed if you assign them to the variable but does not show in the sidemenu, also use the ngOnchanges but it seems that only enter once bone when you start the App. And does not re-enter onchanges. Not really how to update that although it is something simple for the application, I do not manage to get it,

I don’t see anywhere that you mentioned anything about constructors previously, and I’m having a really hard time following what you are saying. Maybe somebody else can understand you, but if I’m going to be able to do anything further I’m going to need to see a complete code repo that reproduces the issue.

export class MyApp {

public itemList: Array;
@ViewChild(Nav) nav: Nav;
public database: SQLite;
rootPage : any ;
public rol =’’ ;
private storage: SQLite;
private isOpen: boolean;
public name = ‘’;
public email= ‘’ ;
public toast : any ;
public alert : any ;
public backButtonPressedOnceToExit ;

public backPressed = false;

public pagesEstudinate: Array<{title: string, component: any, icon: string}>= [];
public pagesDocente: Array<{title: string, component: any, icon: string}> = [];
public pagesPadre: Array<{title: string, component: any, icon: string}> = [];

constructor(
public menuCtrl : MenuController,
public events: Events,
public getUser : Sdmenu,
public alertCtrl: AlertController,
public toastCtrl: ToastController,
public lStorage : Storage ,
public padreService: PadreService,
public ngZone : NgZone,
public ref : ApplicationRef ,
public platform: Platform,
public login : Login,
public datab : Database) {
this.actualizarnombre();
this.load();
this.consultDb();
this.getToken();

if(!this.isOpen){
   this.storage = new SQLite();
   this.storage.openDatabase({name: "estudioeducativo.db", location: "default"}).then(
     ()=> {
        this.isOpen = true;

     });
 }
platform.ready().then(() => {
  platform.triggerReady
      platform.registerBackButtonAction(() => {
        if (this.backButtonPressedOnceToExit) {
          this.platform.exitApp();
        } else if (this.nav.canGoBack()) {
          this.nav.pop({});
        } else {
          this.showToast();
          this.backButtonPressedOnceToExit = true;
          setTimeout(() => {

            this.backButtonPressedOnceToExit = false;
          },2000)
        }
      });
    });


this.itemList = [];
this.pagesEstudinate = [
      { title: 'Horario', component: HorarioPage, icon : 'calendar' },
      { title: 'Calificaciones', component: CalificacionesPage, icon : 'create' },
      { title: 'Correo', component: CorreoPage, icon : 'mail' },
      { title: 'Inasistencias', component: InasistenciasPage, icon : 'list-box' },
      { title: 'Observaciones', component: ObservacionesPage, icon : 'person' },
      { title: 'Simulacros', component: SimulacrosPage , icon : 'megaphone'}
    ];
    this.pagesDocente = [

      { title: 'Horario', component: DocenteHorarioPage, icon : 'calendar' },
      { title: 'Horario De Grupos', component: HorarioPage, icon : 'people' },
      { title: 'Correo', component: CorreoPage, icon : 'mail' },
      { title: 'Registrar Inasistencia', component: DocInasistenciasPage, icon: 'list-box'},
      { title: 'Registrar Observación', component: DocObservacionesPage, icon: 'person'},
    ];
    this.pagesPadre = [
      { title: 'Seleccionar hijo', component: PadreSlctHijoPage, icon : 'arrow-dropright' },
      { title: 'Horario', component: HorarioPage, icon : 'calendar' },
      { title: 'Calificaciones', component: PadreCalificacionesPage, icon : 'create' },
      { title: 'Correo', component: CorreoPage, icon : 'mail' },
      { title: 'Inasistencias', component: PadreInasistenciasPage, icon : 'list-box' },
      { title: 'Observaciones', component: PadreObservacionesPage, icon : 'person' },
    ];

}

ngOnChanges() {

}
showAlert() {
this.alert = this.alertCtrl.create({
title: ‘Salir?’,
message: ‘Desea salir de la app?’,
buttons: [
{
text: ‘Cancel’,
role: ‘cancel’,
handler: () => {
this.alert =null;
}
},
{
text: ‘Exit’,
handler: () => {
this.platform.exitApp();
}
}
]
});
this.alert.present();
}

showToast() {
let toast = this.toastCtrl.create({
message: ‘Presiona otra vez para salir’,
duration: 2000,
position: ‘bottom’
});

    toast.onDidDismiss(() => {
      console.log('Dismissed toast');
    });

    toast.present();
  }

public getToken(){
if (typeof FCMPlugin != ‘undefined’) {
FCMPlugin.getToken((token) => {
console.log(“token de primera vez”, token);
this.lStorage.set(‘tokenFCM’,token)
}, (error) => {
console.log('error retrieving token: ’ + error);
});

  FCMPlugin.onTokenRefresh(function(token){
    console.log("nuevo Token: ",token);
    console.log("el de storage", this.lStograge.getItem('tokenFCM'));
    this.lStorage.set('tokenFCM',token);
  });
}    

}
public load() {
NativeStorage.getItem(‘user’).then(
data=>{
console.log("datos: ",data);
switch (this.rol) {

          case "docente":
            this.rootPage = DocenteHorarioPage;
            break;
          case "estudiante":
          this.rootPage = HorarioPage;
            break;
            case "acudiente":
          this.rootPage = InicioPadrePage;
            break;
        }
        
    }, (error)=>{
      this.nav.setRoot(LoginPage);
}); 
   
}

openPage(page) {

this.nav.setRoot(page.component);

}

logout(){
this.name = ‘’;
this.email = ‘’;
this.rol = ‘’;
this.datab.deleteUser().then((result)=>{
console.log("borró: ",result);

    }, (error)=> {
      console.log("hay error en borrar ", error);
      
    });
NativeStorage.remove('user');
NativeStorage.clear();
this.datab.deleteHorasG();
this.datab.deleteHorario();
this.nav.setRoot(LoginPage);

}
public consultDb(){
this.datab.getUser().then((result) => {
console.log(“trae info”);

    }, (error) => {
        console.log("no trae el rol : ", error);
    });

}
public actualizarnombre(){
NativeStorage.getItem(‘user’).then(
data=>{
this.rol = data.rol;
this.name = data.name;
this.email = data.email;

    }, (error)=>{
      console.log(error);
      
}); 

}

}

Login.ts
public load() {
this.datab.getUser().then((result) => {
switch (result[0].rol_name) {
case “docente”:
this.navCtrl.setRoot(MyApp);
this.events.publish(‘nuevoU’,result);
break;
case “estudiante”:
this.navCtrl.setRoot(MyApp);
this.events.publish(‘nuevoU’,result);
break;
case “acudiente”:
this.navCtrl.setRoot(MyApp);
this.events.publish(‘nuevoU’,result);
break;
}
}, (error) => {
console.log("no trae el rol : ", error);
});
}

I thought I said sorry

Move everything you are doing in the constructor before the call to platform.ready into the then block after it. All of that stuff needs the platform to be ready. Also, in the future, please use three backticks to make code fences:

muchMoreReadable() {
  eyesNotBleeding();
}
1 Like