Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 4 - How to route to a particular component when back button is pressed?

I want to route to a particular path when the back button will be clicked in the browser.

I was trying the following code snippet. But it changes the URL to the desired one for just a moment, and then routing to the previous actual URL.

constructor(location: PlatformLocation, private router: Router) {
    location.onPopState(() => {
        router.navigate(['/home']);
    });
}
like image 587
aniket7824 Avatar asked Aug 12 '17 17:08

aniket7824


People also ask

How do you navigate to the previous page programmatically?

navigate(LASTPAGE); For example, page C has a Go Back button, Page A -> Page C, click it, back to page A. Page B -> Page C, click it, back to page B.

How do you access the parameters passed to a route in angular?

The first way is through the route snapshot. The route snapshot provides the initial value of the route parameter map (called the paramMap ). You can access the parameters directly without subscribing or adding observable operators. The paramMap provides methods to handle parameter access like get , getAll , and has .


1 Answers

I found the solution in some different way and using JavaScript.

Suppose I am currently in "/menu" and I want to navigate to "/home" when the back button will be pressed. Check the following code snippet.

ngOnInit() {
window.history.pushState( {} , 'Home', '/home' );
window.history.pushState( {} , 'Menu', '/menu' ); }

Here I am pushing two states in window.history inside ngOnInit(). Firstly the URL (/home) I want to visit on the back key press and then the current URL (/menu).

It is working well and I had achieved what I want.

like image 183
aniket7824 Avatar answered Sep 29 '22 00:09

aniket7824