Search code examples
angulartypescriptionic-framework

Ionic not destroying pages after leaving it


I started working with Ionic (TypeScript + Angular) due to some needs on my job, I never coded for mobile before, this is my first time ever.

I got stuck with a issue that I got no idea how to fix it, let me try to explain the flows:

Flow 1

  1. UserA sign in with their user/password
  2. UserA is redirected to the profile page after the login
  3. UserA do logout

Flow 2

  1. UserB sign in with their user/password
  2. UserB is redirected to the profile page after the login (and he see the UserA profile info)

Considerations

I'm storing the session with @ionic/storage BUT has nothing to do with storage issues, I know that because after the logout I tried to await session.get('user') and it returns undefined, and after the new login I await session.get('user') and it shows the right user (the one that just connected)

What I think it is?

I think that ionic is holding the page on the cache, when a new user sign the methods constructor and ngOnInit is not called again... the variables stays with the old user data and the view is rendered with wrong information.

I'm kinda sure this is the problem because is not every time that this bug happens, sometimes everything is rendered as it should be in the first place, but I don't know what to do :/

Questions

Someone already had this issue? What did you do to fix this issue?

There is a way for me to tell ionic not to keep the page in cache?

There is a way to force the last content be destroyed after router.navigate() to another page?


Solution

  • By default, Ionic does not destroy pages - it keeps them in the DOM to enable travel via the back/forward buttons. In vanilla Angular routing, you can control this via RouteReuseStrategy but if you’re using ion-router-outlet, you cannot. ion-router-outlet implements a stack that stores navigation history, and will only run Ionic lifecycle hooks after a component has been created. You can use navigateRoot() to clear this stack, or switch to Angular’s router-outlet and router instead.

    This is a significant flaw in my opinion, and is not documented well enough. There are many cases where it is not desirable to store a rendered component in the DOM indefinitely, and potentially can have significant performance impacts.