diff --git a/packages/angular/common/src/providers/platform.ts b/packages/angular/common/src/providers/platform.ts index e01c6edb77b..387e378317c 100644 --- a/packages/angular/common/src/providers/platform.ts +++ b/packages/angular/common/src/providers/platform.ts @@ -1,5 +1,6 @@ import { DOCUMENT } from '@angular/common'; import { NgZone, Inject, Injectable } from '@angular/core'; +import type { DestroyRef } from '@angular/core'; import { getPlatforms, isPlatform } from '@ionic/core/components'; import type { BackButtonEventDetail, KeyboardEventDetail, Platforms } from '@ionic/core/components'; import { Subscription, Subject } from 'rxjs'; @@ -7,9 +8,18 @@ import { Subscription, Subject } from 'rxjs'; // TODO(FW-2827): types export interface BackButtonEmitter extends Subject { + /** + * @param priority Handlers with a higher priority run first. + * @param callback Called with a function that passes control to the next handler. + * @param [destroyRef] Optionally unsubscribe when this `DestroyRef` is destroyed. For a page + * in an `ion-router-outlet` that is when the page is popped off the stack, not when it is + * navigated away from. + * @returns the subscription, which can also be unsubscribed by hand. + */ subscribeWithPriority( priority: number, - callback: (processNextHandler: () => void) => Promise | void + callback: (processNextHandler: () => void) => Promise | void, + destroyRef?: DestroyRef ): Subscription; } @@ -62,10 +72,14 @@ export class Platform { constructor(@Inject(DOCUMENT) private doc: any, zone: NgZone) { zone.run(() => { this.win = doc.defaultView; - this.backButton.subscribeWithPriority = function (priority, callback) { - return this.subscribe((ev) => { + this.backButton.subscribeWithPriority = function (priority, callback, destroyRef) { + const subscription = this.subscribe((ev) => { return ev.register(priority, (processNextHandler) => zone.run(() => callback(processNextHandler))); }); + + destroyRef?.onDestroy(() => subscription.unsubscribe()); + + return subscription; }; proxyEvent(this.pause, doc, 'pause', zone);