如何从子路由导航到父路由?

我的问题很经典。我有一个应用程序的私有部分是后面的一个 login form。登录成功后,它会转到管理应用程序的子路由。

My problem is that I can't use the global navigation menu because the router tries to route in my AdminComponent instead of my AppCompoment. So my navigation is broken.

另一个问题是,如果有人想直接访问 URL,我想重定向到父“登录”路由。但我做不到。在我看来,这两个问题是相似的。

知道怎么做吗?

146864 次浏览
constructor(private router: Router) {}


navigateOnParent() {
this.router.navigate(['../some-path-on-parent']);
}

路由器支持

  • 绝对路径 /xxx-在根组件的路由器上启动
  • relative paths xxx - started on the router of the current component
  • relative paths ../xxx - started on the parent router of the current component

你想要一个链接/HTML 还是你想路由命令/在代码?

Link : RouterLink 指令总是将提供的链接视为当前 URL 的增量:

[routerLink]="['/absolute']"
[routerLink]="['../../parent']"
[routerLink]="['../sibling']"
[routerLink]="['./child']"     // or
[routerLink]="['child']"


// with route param     ../../parent;abc=xyz
[routerLink]="['../../parent', {abc: 'xyz'}]"
// with query param and fragment   ../../parent?p1=value1&p2=v2#frag
[routerLink]="['../../parent']" [queryParams]="{p1: 'value', p2: 'v2'}" fragment="frag"

使用 RouterLink 时,请记住导入和使用 directives数组:

import { ROUTER_DIRECTIVES } from '@angular/router';
@Component({
directives: [ROUTER_DIRECTIVES],

命令 : navigate()方法需要一个起点(即 relativeTo参数):

import { Router, ActivatedRoute } from '@angular/router';
...
constructor(private router: Router, private route: ActivatedRoute) {}
...
this.router.navigate(["/absolute/path"]);
this.router.navigate(["../../parent"], {relativeTo: this.route});
this.router.navigate(["../sibling"],   {relativeTo: this.route});
this.router.navigate(["./child"],      {relativeTo: this.route}); // or
this.router.navigate(["child"],        {relativeTo: this.route});


// with route param     ../../parent;abc=xyz
this.router.navigate(["../../parent", {abc: 'xyz'}], {relativeTo: this.route});
// with query param and fragment   ../../parent?p1=value1&p2=v2#frag
this.router.navigate(["../../parent"], {relativeTo: this.route,
queryParams: {p1: 'value', p2: 'v2'}, fragment: 'frag'});


// navigate without updating the URL
this.router.navigate(["../../parent"], {relativeTo: this.route, skipLocationChange: true});

从2017年春季开始,这似乎对我有效:

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

Where your component ctor accepts ActivatedRoute and Router, imported as follows:

import { ActivatedRoute, Router } from '@angular/router';

导航到父 组件,而不管当前路由或父路由中的参数数目: 角度6更新1/21/19

   let routerLink = this._aRoute.parent.snapshot.pathFromRoot
.map((s) => s.url)
.reduce((a, e) => {
//Do NOT add last path!
if (a.length + e.length !== this._aRoute.parent.snapshot.pathFromRoot.length) {
return a.concat(e);
}
return a;
})
.map((s) => s.path);
this._router.navigate(routerLink);

这样做还有一个额外的好处,那就是它是一个绝对路由器,你可以使用单例路由器。

(角度4 + 是肯定的,可能还有角度2。)

我的路线是这样的:

  • User/Edit/1-> Edit
  • User/Create/0-> Create
  • 用户/-> 名单

当我在编辑页面,例如,我需要回到列表页面,我将返回2级上的路线。

考虑到这一点,我创建了一个带有“ level”参数的方法。

goBack(level: number = 1) {
let commands = '../';
this.router.navigate([commands.repeat(level)], { relativeTo: this.route });
}

因此,从编辑到列表,我调用这样的方法:

this.goBack(2);

You can navigate to your parent root like this

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

您将需要在构造函数中注入当前活动的 Route

constructor(
private router: Router,
private activeRoute: ActivatedRoute) {


}

另一种方式可能是这样的

this._router.navigateByUrl(this._router.url.substr(0, this._router.url.lastIndexOf('/'))); // go to parent URL

这是构造函数

constructor(
private _activatedRoute: ActivatedRoute,
private _router: Router
) { }

事不宜迟:

this.router.navigate(['..'], {relativeTo: this.activeRoute, skipLocationChange: true});

参数 '..'使导航向上一级,即父级:)

如果使用 uiSref 指令,那么可以这样做

uiSref="^"

我的解决办法是:

const urlSplit = this._router.url.split('/');
this._router.navigate([urlSplit.splice(0, urlSplit.length - 1).join('/')], { relativeTo: this._route.parent });

还有 Router注射液:

private readonly _router: Router

这些对我来说都不管用... 下面是我的 back 函数代码:

import { Router } from '@angular/router';
...
constructor(private router: Router) {}
...
back() {
this.router.navigate([this.router.url.substring(0, this.router.url.lastIndexOf('/'))]);
}

this.router.url.substring(0, this.router.url.lastIndexOf('/') --> get the last part of the current url after the "/" --> get the current route.

Everyone suggesting using relative paths really forgets about the most important part: the relative path always depends on the (possible) params you have in your route.

例如,如果您有一个子路由 edit/:id,并且您的 id 是一个类似于 /api/something/123格式的 URI,那么为了使用相对路由到达您的父路由,您需要使用 [../../../..']。 换句话说,将 URL 视为计算机上的目录结构。不要根据路由表中创建的定义来考虑路由。