Force back button route when logging out (ionic 4)


#1

Hi all,

I am having a little issue with the ion-back-button where if I do a manual route to the login page (e.g. someone clicks ‘logout’) it shows the back button ok but on press sends you back to the member area, which is now not allowed. I guess this makes sense as its just going back in the history, but is there a way to either force the back button path in that instance or remove it all together?

I am just using the default back button as so:

<ion-buttons slot="start">
      <ion-back-button defaultHref="home"></ion-back-button>
    </ion-buttons>

Has anyone had this issue?

Thanks


#2

I think this is the key: how are you “doing a manual route”?


#3

When programatically doing something like this:

this.router.navigate(['login']);


#4

You’re bypassing the Ionic navigation system when you interact directly with the router like that. So one thing you could try is instead injecting NavController and calling its setRoot() function, which should reset the Ionic nav stack (and presumably nuke the back button).


#5

Is that still available in Ionic 4? According to the docs it is (which I’ve found unreliable anyway) but when I import NavController I just get an error that setRoot is not a function.

Very simplified copy:

import {NavController} from '@ionic/angular';

constructor(
        ...
        private nav: NavController
) { ... }

function() {
    this.nav.setRoot();
}

Results in the error this.nav.setRoot is not a function


#6

How about navigateRoot?

No, looking at the source I would be surprised if that worked. How about:

this.router.navigate(['login'], {replaceUrl: true});

#7

Actually navigateRoot did work, except that it didn’t transition back to /login, it just went straight there.

Your second example of {replaceUrl: true} didn’t work but this {skipLocationChange: true} seems to do the same as navigateRoot which I think its slightly better in that it looks like NavController is deprecated.

It would be nice to have the transition but this works for now.

Edit: having said that, it seems to stop the URL from changing to the correct location - perhaps not a problem when this is actually compiled into an app?


#8

Thinking about it, it’s probably safe to just have a manual back button on login that always goes to home - its not as nice as just using the ion-back-button but would prevent this issue?