Working with Events on Ionic 5

Hi everyone,

Here is a small blog post where I needed to work on an Ionic v5 project where (Angular) events were/are not working anymore.

Context: Basically, I was working on the side-menu ‘starter’ where I wanted the side-menu to automatically update with the user’s username after logging in.

Beforehand, in order to use the Events, it was as simple as:

import { Events } from '@ionic/angular';

And finally work on your logic, but this got removed in Ionic 5. You can see the changelog here: https://github.com/ionic-team/ionic/blob/45d03baf981d0e10eb1fe689908532adef2ba31d/BREAKING.md#events-1

In order to have similar result, create a new service, in our case EventsService (using ionic generate service) like this:

import {Injectable} from '@angular/core';
import {Subject} from 'rxjs';

@Injectable({
    providedIn: 'root'
})
export class EventsService {
    private fooSubject = new Subject<any>();

    publishSomeData(data: any) {
        this.fooSubject.next(data);
    }

    getObservable(): Subject<any> {
        return this.fooSubject;
    }
}

In my case, I needed to publish the user’s id just after logging in to the side-menu component. After checking that the user was properly logged in, I was able to publish the data.

import { EventsService } from './events.service';

export class LoginPage implements OnInit {

  constructor(
    public events: EventsService,
  ) { }

  login(username: string, password: string) {
    [...] // login mechanism
    this.events.publishSomeData({
      userId: this.userIdToLogin
    })
  }

On the other side (in my other component), basically when the app gets instanciated, I will have an observable on the events.

import { EventsService } from './events.service';

[...]

export class AppComponent implements OnInit {

  constructor(
    [...]
    private events: EventsService
  ) {
    this.initializeApp();
  }

  initializeApp() {
    this.platform.ready().then(() => {
      this.statusBar.styleDefault();
      this.splashScreen.hide();
    });

    this.events.getObservable().subscribe((data) => {
      console.log("Data received:", data);
      this.reviewerService.getReviewer(data.userId).snapshotChanges().subscribe(res => {
        this.userProfile = res.payload.toJSON();
      });
    })
  }

And… you’re good to go!