Ionic 7 Angular PWA: Browser back button calls ngOnInit another time, creating two pages in memory

47 Views Asked by At

I have an Ionic 7 angular PWA with a Tabs structure. One of my tabs loads a page that initializes a google map plugin from capacitor.

When I cycle through the tabs several times everything is smooth as expected. The map does not need to reload each page visit. Its always there once ngOnInit is called the first time.

However I cannot stop anyone from hitting the browser back button or swiping back on android. This is a PWA (Progressive Web App). If someone hits the back button to navigate back to the map view things get weird. The Constructor and ngOnInit are called again and the map is not still there. It will eventually load the page.

Interestingly... There is a on click callback for each marker on the map that launches a modal. In this callback i console.log(this).

One I go through the reloading of the map page caused by the back button and click on one of the marker, the modal will not fire and surprisingly, two MapPages (this) are printed to the screen.

If I use the back button to navigate to the map page 4 times, the single callback on click will print for MapPages.

I feel like I am fundamentally confused and implementing something wrong even though I've just followed ionics generated tabs project structure.

I have even seen other stack overflow users trying to figure out HOW to get ngOnInit to fire when they hit the back button. The confusion is overwhelming.

This happens on mobile and browser. Any thoughts or Ideas? Thanks in advance

Docs say Ionic does not tear down pages once visited. This page only tears down the DOM, the page itself stays in memory and recreates itself each time. I've tried using ionic lifecycle hooks but that more explicitly slows the app by recreating it every page visit, not just On Back.

1

There are 1 best solutions below

0
Wilt On

When using Ionic you should probably reconsider using the Angular life-cycle events and instead use the Ionic life-cycle events instead.

Check here for more information: https://ionicframework.com/docs/angular/lifecycle

Without more information or a code example it is hard to help you more than that.