Calling a function in app.component.ts from another component

0
1436

Someone in the Ionic Slack technical-questions channel last night asked how you call functions in app.component.ts from another Page.  I was happy to help out.

The answer (well, the way I do this anyway) is to subscribe to an event in your app.component.ts and publish that event from the page you want to call the function from.

in app.component.ts :

import { Events } from 'ionic-angular';

constructor(public events: Events) {
events.subscribe('user:login', () => {
  this.loggedIn();
});
}

loggedIn() {
console.log("logged in");
}

in the calling Page:

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

logIn() {
events.publish('user:login');
}

The calling page fires the event which is subscribed to in app.component.  See the Ionic Conference app to see an example of event handling in app.component.ts.

Objects can also be passed as parameters with events like this which can be really handy.

For more info on Events see the official Ionic documentation here.

LEAVE A REPLY

Please enter your comment!
Please enter your name here