首页 > 解决方案 > 使用角度路由器实现简单的后退导航

问题描述

我想在我的标题中实现一个后退按钮:它将从子路由移回父路由!

假设我有以下嵌套路由:/ => /bar => /bar/foo

现在,如果我在我的 Foo 组件中添加一个“返回”按钮,我可以简单地做

 this.router.navigate([".."], { relativeTo: this.activatedRoute });

但是,在我的情况下,后退按钮位于标题(AppComponent)中,这意味着上面的代码不起作用,我猜 ActivatedRoute 指向/

堆栈闪电战

所以,我的问题是,如何在没有 ActivatedRoute 的情况下导航回(从子到父)?

更新:我仍在研究这个解决方案,我觉得它应该可以工作(但现在不行):

 const activatedRoute = this.injector.get(ActivatedRoute);
 this.router.navigate(['..'], { relativeTo: activatedRoute });

斯塔克布利茨

标签: angularangular-routing

解决方案


你应该试试Location服务

import { Component } from "@angular/core";
import { Location } from "@angular/common";

@Component({
  selector: "my-app",
  template: `
    <div class="container">
      <button (click)="goBack()">Go Back</button><br />
      <a routerLinkActive="active" routerLink="/bar">Bar</a>

      <router-outlet></router-outlet>
    </div>
  `,
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  constructor(private location: Location) {}

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

推荐阅读