Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the browser's back button to take me to my previous URL? (angular ui-router)

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?

like image 804
Zack Avatar asked Jan 28 '16 16:01

Zack


People also ask

How do I find the previous route URL?

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!

How can I get current URL in angular?

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.

Can we add RouterLink to button?

Using Router linksAfter Angular v4 we can directly add a routerLink attribute on the anchor tag or button.


1 Answers

Please take a look at the following SO answer there are four steps to take

  1. Unique Urls
  2. A session service
  3. A state history
  4. And a location service
like image 62
Jordy van Eijk Avatar answered Oct 01 '22 02:10

Jordy van Eijk