Angular2: navigate to a route and pop back to the root of the pushState stack

Issue

Using Angular2 routing, how can I navigate to some route, while having the pushState pop all the way back to the root?

I looked into the router.navigate([...]) method of Router, but didn’t find it there.

For example, in Dart’s route_hierarchical Router, I could do
router.go('login',{},replace: true,startingFrom:router.root);

Solution

Until Angular2 provides this functionality in it’s Router, here’s a temporary workaround:

abstract class Hist {
  static int _initialLength;
  // Call this ASAP when app starts.
  static void setAsInitialLength() {
    _initialLength = window.history.length;
  }
  static Future goBackToRoot() async {
    Completer completer = new Completer();
    window.history.go(-(window.history.length-_initialLength));
    Timer.run((){
      completer.complete();
    });
    return completer.future;
  }
}

Then I can use it like this:

await Hist.goBackToRoot();
router.navigate(['/Main',{}]);

Answered By – Alon Amir

Answer Checked By – Cary Denson (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *