Ionic: navigate from a local notification

Everyone loves alarms! And everyone wants to be going places. So how do you send your loyal app-folk to a specific page from a local notification?

If you’re using the current Ionic Framework (v4 at time of writing) with Angular (v7), plus the Local Notifications plugin & Ionic Native lib, maybe not easily.

If your notification pops up but your code to handle it by navigateForward()‘ing to a new page does nothing, you might have fallen foul of a gotcha with Angular’s scope of execution, since the plugin’s .on('click') proceed via a subscribe() callback.

Fortunately looking into this with adb logcat gives a surprisingly helpful error message if you can find it, making it a bit less painful to debug than some native plugin issues.

Sift through the logs (or take my word for it) and you might find:

Navigation triggered outside Angular zone, did you forget to call ‘ngZone.run()’?

And happily, at least with my setup for When.fm, that was indeed all that’s needed. The custom service that handles set reminder alarms just needs a little extra NgZone wrapper to get the required execution context, and of course the Angular service to support it.

My working code:

import { Injectable, NgZone } from '@angular/core';
import { Events, NavController } from '@ionic/angular';
import { LocalNotifications } from '@ionic-native/local-notifications/ngx';
...

export class AlarmProvider {

  constructor(
    ...
    private localNotifications: LocalNotifications,
    public nav: NavController,
    private ngZone: NgZone,
    ...
  )
...
  public add(...) {
    ...
    this.localNotifications.schedule(...)

    // Notification tapped
    const nav = this.nav;
    this.localNotifications.on('click').subscribe(notificationReceived => {
        this.ngZone.run(() => {
          nav.navigateForward(`/event/${notificationReceived.data.eventId}/programme/set/${notificationReceived.data.setId}`);
        });
      });
    ...
  }
}

Voilà, a notification that navigates anywhere you’d like when tapped.

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.