Tutorial

Using Events in Ionic to Pass Data & Messages Between Pages

Published on March 26, 2018
    Default avatar

    By Christian Lopez

    Using Events in Ionic to Pass Data & Messages Between Pages

    While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

    Events in Ionic is a pub-sub system that can be used to pass messages across different components and pages. Here we’ll go over a simple example where a page publishes an event and a second page subscribes to that event. This way, data can easily be passed between the two.

    Injecting the Events Service

    The first step in getting the event system to work is to import and inject the Events service into both the sending and the receiving pages:

    page1.ts
    import { Component, Events } from 'ionic-angular';
    
    
    
    page2.ts
    import { Component, Events } from 'ionic-angular';
    
    
    

    Here we named the injected instances events1 and events2 for clarity, but they can both be injected using the same name since each instance is part of a different page class.

    Publishing & Subscribing to Events

    Now that we have imported and injected the Events service into both pages we can start publishing and subscribing to events using the service’s publish and subscribe methods.

    On Page1, we’ll publish a message when a button is pressed:

    page1.ts
    handleClick(){
      this.events1.publish('my-message', '👋 Hello from page1!');
    }
    

    Then on page 2 we’ll subscribe to receive messages published using the my-message key (called a topic in Ionic):

    page2.ts
    constructor(public events2: Events){
      this.events2.subscribe('my-message', (data) =>{
        console.log(data); // 👋 Hello from page1!
      });
    }
    
    

    As soon as the event is published and page2 is initialized, the subscribe event will be triggered and execute the code with the data being passed.

    Note that the data sent using publish doesn’t have to be a string and can just a well be an object.

    Practical Application

    There are many practical applications to use the event system. For example, I’ve used it to pop back to a page using the navController while also updating some information on the page that gets popped into.

    Normally, when navigating to a page using navController’s push method, we can pass data as navParams, but the pop method doesn’t have such capability, so the event pub-sub service comes-in really handy.

    Take a look at this mini application for instance:

    game.ts
    import { Component, Events } from 'ionic-angular';
    import { NavController } from 'ionic-angular';
    
    @Component({
      selector: 'page-game',
      templateUrl: 'game.html'
    })
    export class GamePage {
      constructor(
        public events: Events,
        public navController: NavController
      ) {
        this.events.subscribe('stats', statsData => {
          console.log(statsData);
        });
      }
    
    
    show-winner.ts
    import { Component, Events } from 'ionic-angular';
    import { NavController } from 'ionic-angular';
    
    @Component({
      selector: 'page-show-winner',
      templateUrl: 'show-winner.html'
    })
    export class ShowWinnerPage {
      constructor(
        public events: Events,
        public navController: NavController
      ) {}
    
    

    Unsubscribing

    The events service in the GamePage class will continue to be subscribed to receive messages for the life of the application unless it is unsubscribed using something like this:

    game.ts
    private unsubscribeToEvents() {
      this.events.unsubscribe('stats', () => {
        console.log('Unsubscribed!');
      });
    }
    
    

    Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

    Learn more about us


    About the authors
    Default avatar
    Christian Lopez

    author

    Still looking for an answer?

    Ask a questionSearch for more help

    Was this helpful?
     
    Leave a comment
    

    This textbox defaults to using Markdown to format your answer.

    You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

    Try DigitalOcean for free

    Click below to sign up and get $200 of credit to try our products over 60 days!

    Sign up

    Join the Tech Talk
    Success! Thank you! Please check your email for further details.

    Please complete your information!

    Get our biweekly newsletter

    Sign up for Infrastructure as a Newsletter.

    Hollie's Hub for Good

    Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

    Become a contributor

    Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

    Welcome to the developer cloud

    DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

    Learn more
    DigitalOcean Cloud Control Panel