Angular2, relative navigation (two levels back ../

2019-07-31 05:11发布

I have a back button in my application, which navigates relatively some levels back. In case of one level

this.router.navigate(['..'], { relativeTo: this.route });

it works perfectly (resulted route url:http://localhost:3000/three/two/one). In case of two level back rel. navigation

this.router.navigate(['..', '..'], { relativeTo: this.route });

router navigates two levels back, BUT the resulted route url looks now like http://localhost:3000/three/two/(tailing slash, which is not correct).

Am I doing something wrong or could it be a bug?

2条回答
看我几分像从前
2楼-- · 2019-07-31 05:38

In case of two levels down use this:

this.router.navigate(['../../'], { relativeTo: this.route });
查看更多
【Aperson】
3楼-- · 2019-07-31 05:44

Use the Location.back() method instead, Location.back() method takes you to the last page in your browsers history.

in your component:

import { Location }  from '@angular/common';
//some othe code ......
//in your class
constructor(private location: Location) {}

//create a method to go back
goBack() {
  this.location.back();
}

Now create a back button in your component.html and bind this method to it:

<button (click)="goBack()" > Back </button> 
查看更多
登录 后发表回答