diff --git a/packages/angular/common/src/providers/platform.ts b/packages/angular/common/src/providers/platform.ts index e01c6edb77b..b60981b185a 100644 --- a/packages/angular/common/src/providers/platform.ts +++ b/packages/angular/common/src/providers/platform.ts @@ -1,5 +1,7 @@ import { DOCUMENT } from '@angular/common'; import { NgZone, Inject, Injectable } from '@angular/core'; +import type { DestroyRef } from '@angular/core'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { getPlatforms, isPlatform } from '@ionic/core/components'; import type { BackButtonEventDetail, KeyboardEventDetail, Platforms } from '@ionic/core/components'; import { Subscription, Subject } from 'rxjs'; @@ -9,7 +11,13 @@ import { Subscription, Subject } from 'rxjs'; export interface BackButtonEmitter extends Subject { subscribeWithPriority( priority: number, - callback: (processNextHandler: () => void) => Promise | void + callback: (processNextHandler: () => void) => Promise | void, + /** + * Pass a component's `DestroyRef` to have the subscription torn down with that + * component. Without it the subscription lives for the lifetime of the injector, + * which for a root-provided `Platform` means the lifetime of the application. + */ + destroyRef?: DestroyRef ): Subscription; } @@ -62,8 +70,10 @@ 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 source$ = destroyRef ? this.pipe(takeUntilDestroyed(destroyRef)) : this; + + return source$.subscribe((ev) => { return ev.register(priority, (processNextHandler) => zone.run(() => callback(processNextHandler))); }); };