ramashish tomar
ramashish tomar

Reputation: 873

how to show user name in menu

I have a {{user_name}} variable in my app.component.ts and I want to use it for displaying the user name which I am getting from local storage after the user logs in.

But this loads only at app start and I want to reload it after the user logs in. When I close and reopen app after log in it works fine and user name displayed. But at first, it shows only "hi" and doesn't show the user name.

<ion-menu [content]="content" >
    <ion-header>
      <ion-toolbar>
        <ion-title>
            <p>
            HI! {{user_name}}
        </p></ion-title>
      </ion-toolbar>

    </ion-header>

    <ion-content>

      <ion-list >

        <button menuClose ion-item *ngFor="let p of pages" (click)="openPage(p)">
          {{p.title}}

        </button>
        <button  menuClose ion-item (click)="logout()" >
          Log Out
        </button>
      </ion-list>

    </ion-content>

  </ion-menu>

  <!-- Disable swipe-to-go-back because it's poor UX to combine STGB with side menus -->
  <ion-nav [root]="rootPage" #content swipeBackEnabled="false"></ion-nav>

I know that i can publish an event at user loged in , but how to reload the menu after receiving the event

Upvotes: 3

Views: 2196

Answers (1)

Whatatimetobealive
Whatatimetobealive

Reputation: 1353

I had a pretty similar case, in my opinion events are the best way to go:

app.component.ts

   import { ..., Events } from 'ionic-angular'; //First import events

   constructor(
    ...
    public events: Events,
    ...
    ){
        .....
        events.subscribe('user:created', (user) => {

          this.user_name=user.name;

        });

     ...
    }

Now your able to change that value anywhere in the app using this.events.publish('user:created', user);

For example:

login.ts

    import { Your other imports...,Events} from 'ionic-angular';

    constructor(
      ...
      public events: Events,
      ...
      ) {}

     // let's assume you did your login and have an user array which has user.name in it,
     // pass that data like this

     updateUserInfo(user){
      this.events.publish('user:created', user);
     }

It will work as expected. Hope it helps...

Upvotes: 4

Related Questions