angular - 使用角度路由器实现简单的后退导航
问题描述
我想在我的标题中实现一个后退按钮:它将从子路由移回父路由!
假设我有以下嵌套路由:/ => /bar => /bar/foo
现在,如果我在我的 Foo 组件中添加一个“返回”按钮,我可以简单地做
this.router.navigate([".."], { relativeTo: this.activatedRoute });
但是,在我的情况下,后退按钮位于标题(AppComponent)中,这意味着上面的代码不起作用,我猜 ActivatedRoute 指向/
所以,我的问题是,如何在没有 ActivatedRoute 的情况下导航回(从子到父)?
更新:我仍在研究这个解决方案,我觉得它应该可以工作(但现在不行):
const activatedRoute = this.injector.get(ActivatedRoute);
this.router.navigate(['..'], { relativeTo: activatedRoute });
解决方案
你应该试试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();
}
}
推荐阅读
- android - 如何配置 Firebase Crashlytics 以获取 NDK 崩溃报告
- javascript - 以小时为单位设置最小值和最大值 timepicker jquery
- r - 在 R 输出中提取特定结果
- javascript - 速度优化:使用异步优化渲染阻塞脚本
- python - PyGears TypeMatchError:[0],不完整类型:Tuple[Fixp[32],Fixp[32]]
- ruby-on-rails - Ruby 用守卫替换 if 块
- linux - 如何将回显输出同时重定向到 STDOUT 和变量?
- elasticsearch - 匹配 Elastic Search 中存储的值和查询
- javascript - Javascript 在数组中切换显示
- python - 如何在 Python 中的字符串列表末尾删除多个子字符串?