Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ionic 4 Angular router navigate and clear stack/history of previous page

I'm developing an app using Ionic 4 with Angular router. I would like to navigate to another page and clear the page stack. In Android native, it's something like this:

Intent intent = new Intent(NewActivity.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);

From what I've read so far, it is possible using Ionic NavController but it is deprecating in Ionic 4. I learnt about buttons with routerLink but if I'm not mistaken, by using that the app will immediately navigate to the other page. I need to execute some logic before navigating to another page .

For example: Login page. After successful login, the user shouldn't be able to go back to the login page. Also, by clicking the 'login' button, it should call a function to process the login and decide to navigate/not navigate to another page.

Is there any way that I can achieve this with Angular router or do I need to rely on the deprecating Ionic NavController?

like image 503
tyn Avatar asked Nov 29 '22 13:11

tyn


2 Answers

For example of a login page, which is a root page ('/login'), after clicking the login button navigate to a new page like this:

onLogin() {
   this.router.navigateByUrl('/profile', { replaceUrl: true }) 
}

It replaces the page history entry with a new URL, in this particular case with '/profile'. After using a plain <ion-back-button></ion-back-button> or the browser's back button, you will not be redirected to the login page but to the preceding page. Let's say your page navigation is like this: home -> login -> profile, but the history will remember only home -> profile, thus hitting the back button at profile page will take you back to home.

For a complete solution, you can combine this with Angular Route Guards, to prevent accessing pages based on some conditions (e.g. user is logged in). Hints how to do it can be found in this answer.

like image 158
Patronaut Avatar answered Dec 11 '22 02:12

Patronaut


this.router.navigateByUrl('/login', { skipLocationChange: true });

Navigates without pushing a new state into history.

https://angular.io/api/router/NavigationExtras

like image 41
Jay Ordway Avatar answered Dec 11 '22 01:12

Jay Ordway