有子路由时如何返回上一页?

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

有子路由时如何返回上一页?

详情请看代码中的注释。谢谢

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}`);
  }
}

关于路由的 angular 2 文档建议您使用 window 对象来代替 https://angular.io/docs/ts/latest/tutorial/toh-pt5.html#!#find-our-way-back

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

Angular 7.2.7 的最新文档(受@Victor 的link 启发)基本上说要使用注入的 Location 服务来实现相同的目的。 https://angular.io/tutorial/toh-pt5#find-the-way-back

(从示例中复制)

在模板中:

<button (click)="goBack()">go back</button>

和组件:

goBack(): void {
  this.location.back();
}