I am doing my frontend routing with angular ui router, and I am seemingly unable to get my browser's back button to take me to most recent URL.
Let me demonstrate.
Let's say I start here
/#/myapp/
And after some clicks, I have dynamically adjusted my URL to become
/#/myapp/12345
Let's say I click a datepicker while remaining on the page
/#/myapp/12345?start=2016-01-21&end=2016-01-28
I am able to do this by using $scope'd functions in tandem with $location.url
Awesome. So far, so good.
Let's say I navigate away from this by clicking
<a href="#"> My App </a>
Which, due to the way I have set up my routing
myApp.config([
'$stateProvider', '$urlRouterProvider',
function($stateProvider, $urlRouterProvider) {
$stateProvider.state('myapp',
url : '/myapp/*id?start&end',
templateUrl : '<path to my template>',
controller : '<name of my controller>'
);
// more routes
$urlRouterProvider.otherwise('/myapp/');
}
]);
will default back to the initial state
/#/myapp
Ok, still so far, so good. However, when I click my browser's back button, I am taken back to
/#/myapp
instead of what I would expect
/#/myapp/12345?start=2016-01-21&end=2016-01-28
I can only guess that the intermediate urls that I have generated while navigating around my page were not captured by my browser's history... which I guess makes sense. How do I get my browser to recognize these intermediate steps so that I can backtrace properly?
In any component you want to access the previous url, you need to import the url service, define it in its constructor, subscribe to the previous url observable, and set it as a variable in the component. Now you can use the previous url anywhere in your component, and receive any changes to its value!
Steps to get current route URL in Angular. Import Router,NavigationEnd from '@angular/router' and inject in the constructor. Subscribe to the NavigationEnd event of the router. Get the current route url by accessing NavigationEnd's url property.
Using Router linksAfter Angular v4 we can directly add a routerLink attribute on the anchor tag or button.
Please take a look at the following SO answer there are four steps to take
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With