Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Edit browser's history API with Angular router

I have an application where we construct a series of temporary data points all with an ID of 0. I reference all these points individually by keying them as 01, 02, 03, etc. My route is /details/:id. If a user saves one of these data points our API creates a real ID. So the process looks something like this to the user:

Go to temp item at /details/0123

Save changes to item 0123.

Receive the new item in the response with an id of 456.

Angular reroutes to /details/456 and the user doesnt notice the transition unless they were paying attention to the URL.

However, if a user hits the Back Button on their browser they will route to /details/0123.

Question: Can I edit the browser history via the Angular router (or some other reliable means) to prevent navigating to /details/0123?

like image 770
JDillon522 Avatar asked Aug 28 '18 12:08

JDillon522


2 Answers

You can replace the route /details/0123 with the route /details/456 in the browser history by adding replaceUrl: true in the NavigationExtras.

Example:

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

like image 123
mahalde Avatar answered Nov 13 '22 13:11

mahalde


What I would do is use Angular's Location and subscribe to the popstate. Something like this:

import {Subscription} from 'rxjs/Subscription';

export class ABC implements OnDestroy {
location: Location;
private subscription: Subscription;

      constructor(location: Location, router: Router) {
        this.subscription = location.subscribe(val => this.router.navigate(/*anywhere*/)
      }
      ngOnDestroy(){
          this.subscription.unsubscribe() //Make sure you do this :)
      }
}

I think that should work for you. Let me know.

like image 26
Vinod Bhavnani Avatar answered Nov 13 '22 12:11

Vinod Bhavnani