Skip to content Skip to sidebar Skip to footer

How To Update Value Inside Ionic 2 Side Menu

How to 'transfer' date from page into side-menu in Ionic2, i.e - Having app.page.html like following:

Solution 1:

ionic2 - using Events

Check out the Events docs

They allow you to 'publish' an action from any page, and subscribe to it in another page to retrieve the value. Your scenario would look a bit like this.

Import (both on Facebooklogin.component and app.component)

import { Events } from 'ionic-angular'; and in your constructor constructor(public events: Events)

Then, whenever you change your userName (f.e. in the handler of the facebook login) publish the value like this.

fbLogin() {
    Facebook.login(["public_profile", "email"])
      .then((resp: FacebookLoginResponse) => {

        if (resp.status === "connected") {
          Facebook.api("/me", ["public_profile", "email"])
            .then(res => {
             this.userName = res.name// publish the username change to the eventsthis.events.publish('username:changed', this.userName);
              this.login({name: this.userName})
            })
        //...
      );
  }

And subscribe to any publishes being made in your app.component

userName: string;

constructor(events: Events) {
   this.userName = "not logged in";

   events.subscribe('username:changed', username => {
      if(username !== undefined && username !== ""){
        this.userName = username;
      }
   }) //... 
}

angular2 - using EventEmitter

import { EventEmitter } from'@angular/core';

public userChanged = newEventEmitter();

fbLogin() {
        Facebook.login(["public_profile", "email"])
          .then((resp: FacebookLoginResponse) => {

            if (resp.status === "connected") {
              Facebook.api("/me", ["public_profile", "email"])
                .then(res => {
                 this.userName = res.name// publish the username change to the eventsthis.userChanged.emit(this.userName);
                 this.login({name: this.userName})
                })
            ...
          );
      }

App.component

import { FacebookLogin } from '../pages/facebook/facebook.component';

public userName;

constructor(fb: FacebookLogin){

    this.userName = "";
    //subscribe to the page's EventEmitterthis.fb.userChanged.subscribe(username => {
       this.userName = username;
    });
}

OR use the EventEmitter as an Output as described in this S.O. answer: What is the proper use of an EventEmitter?

Post a Comment for "How To Update Value Inside Ionic 2 Side Menu"