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

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.

9 thoughts on “Calling a function in app.component.ts from another component

  1. Maria Parker

    Technology never ceases to amaze me. Every other say there are new developments and even more interesting things being talked about for future. Endless possibilities makes me even more curious. Wonderful insights here at you blog. Shall keep watching this space for more! 🙂

    Reply

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s