How to force refresh menu


#1

Hello all,

I’ve a side menu in my application (main class), that for now only have a login or logout button according to the “loggedIn” attribute.

export class MyApp {
  static get parameters() {
    return [[Platform]];
  }

  constructor(platform) {
    this.loggedIn = localStorage.loggedIn;

By default user isn’t logged in, so the login button is displayed.
Once user makes login, I update the value on localStorage, but it takes no effect on updating the menu until I close and reopen the app.

How can I refresh de menu?

Here’s the menu code:

<ion-menu type="overlay" [content]="content">

  <ion-toolbar>
    <ion-buttons start>
      <button menuClose>
        <ion-icon name="ios-arrow-back"></ion-icon>
      </button>
    </ion-buttons>
  </ion-toolbar>

  <ion-content>
    <ion-list>
      <button menuClose ion-item *ngFor="#p of pages" (click)="openPage(p)">
        {{p.title}}
      </button>
      
      <button menuClose ion-item *ngIf="loggedIn" (click)="Wizard.doLogout()">
        Logout
      </button>

      <button menuClose ion-item *ngIf="!loggedIn" (click)="askLogin()">
        Login
      </button>


    </ion-list>
  </ion-content>

</ion-menu>

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

#2

I think you also have to change the value of this.loggedin


#3

Typically then the next question is “how do I get a reference to the application from my login page?”, and this is why tracking things like authentication status in application instance variables is a bad idea. Keep it in a singleton service that can be injected and interacted with in many different situations.


#4

Hi @rapropos,

Thanks for that tip! I’ve implemented and injected my singleton service on my app.
When my app starts, I do login, update singleton and my side menu displays “logout” as expected. (menu page in this case is loaded for the first time after logging in).

But, when I click and do the Logout, even changing the singleton variable (loggedin) to false, it wont change anything on the menu. (probably because the page / menus is already loaded. if I close and reopen the app its ok).

I’ve imported the ApplicationRef on my service and did the .tick() but it didn’t help.

What am I missing?


#5

hi @ahlidap,

You have to use Events to deal with login or logout, because app instance is initialize when app is started.

 this.event.subscribe("user.logout", () => { this.loggedIn = false });

When you do logout,

 this.event.publish("user.logout");