Search code examples
typescriptangularangular2-routing

How to go back to last page when having child router?


How to go back to last page when having child router?

Please see comments in code for details. Thanks

export class OneProductComponent {
  prevUrlPath:string = '';

  constructor(private _router: Router) {}

  routerOnActivate(next:ComponentInstruction, prev:ComponentInstruction) {
    this.prevUrlPath = prev.urlPath;
  }

  goBack() {
    // I have to manually add "products/" here, but if I need 
    // go back to root home page. Then I shouldn't add "products/" here.
    // Is there a smart way to to this?
    this._router.navigateByUrl(`products/${this.prevUrlPath}`);
  }
}

Solution

  • The angular 2 documentation on routing suggests that you use the window object instead https://angular.io/docs/ts/latest/tutorial/toh-pt5.html#!#find-our-way-back

    goBack() {
      window.history.back();
    }