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

Car*_*ert 66 angular-routing angular angular-router

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

我的问题是我无法使用,global navigation menu因为路由器试图在我AdminComponent而不是我的路由AppCompoment.所以我的导航打破了.

另一个问题是,如果有人想直接访问URL,我想重定向到父"登录"路由.但我不能让它发挥作用.在我看来,这两个问题是相似的.

知道如何做到这一点?

Mar*_*cok 119

你想要一个链接/ HTML,或者你想要在代码中强制路由?

链接: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"
Run Code Online (Sandbox Code Playgroud)

使用RouterLink,请记住导入并使用该directives数组:

import { ROUTER_DIRECTIVES } from '@angular/router';
@Component({
    directives: [ROUTER_DIRECTIVES],
Run Code Online (Sandbox Code Playgroud)

势在必行:该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});
Run Code Online (Sandbox Code Playgroud)

  • @Tomato,你需要在路线周围放置[].例如,this.router.navigate(["../../ parent"],{relativeTo:this.route}); (2认同)
  • 当您在 html 中使用 [routerLink] 而不是 typescript 时,如何传递 `relativeTo` 数据? (2认同)

ne1*_*10s 34

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

goBack(): void {
  this.router.navigate(['../'], { relativeTo: this.route });
}
Run Code Online (Sandbox Code Playgroud)

您的组件ctor接受ActivatedRouteRouter导入如下:

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

  • 与其说是日期,不如说是您正在使用的Angular版本会更有用。 (3认同)

Chr*_*the 12

您可以像这样导航到您的父根

this.router.navigate(['.'], { relativeTo: this.activeRoute.parent });
Run Code Online (Sandbox Code Playgroud)

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

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

  }
Run Code Online (Sandbox Code Playgroud)

  • 添加一些解释会使此答案更有用。 (2认同)
  • 此外,当您在两个路径中使用相同的组件时,此答案`this.router.navigate(['.'], {relativeTo: this.activeRoute.parent});` 中的导航方法将正常工作: /users/create 和 /users/edit/123。在这两种情况下,它都会导航到父/用户。使用`this.router.navigate([".."], {relativeTo: this.activeRoute})` 的常规导航仅适用于用户/创建,但不适用于用户/编辑/123,因为它将导航到不存在的 /users/edit/ 路由。 (2认同)
  • +1作为替代方案,但就我个人而言,我有点喜欢字节追逐者,并且会在参数 *[".."]* 中投入一个额外的点,以消除对父级的引用,*{relativeTo: this.route } *。 (2认同)

Joh*_*srk 7

另一种方式可能是这样的

this._router.navigateByUrl(this._router.url.substr(0, this._router.url.lastIndexOf('/'))); // go to parent URL
Run Code Online (Sandbox Code Playgroud)

这是构造函数

constructor(
    private _activatedRoute: ActivatedRoute,
    private _router: Router
  ) { }
Run Code Online (Sandbox Code Playgroud)


kay*_*tea 6

无论当前路线或父路线中的参数数量如何,都要导航到父组件:Angular 6 update 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);
Run Code Online (Sandbox Code Playgroud)

这还有一个额外的好处,就是你可以使用单一路由器的绝对路由.

(Angular 4+肯定,也可能是Angular 2.)


Gün*_*uer 5

constructor(private router: Router) {}

navigateOnParent() {
  this.router.navigate(['../some-path-on-parent']);
}
Run Code Online (Sandbox Code Playgroud)

路由器支持

  • 绝对路径/xxx-在根组件的路由器上启动
  • 相对路径xxx-在当前组件的路由器上启动
  • 相对路径../xxx-从当前组件的父路由器开始


小智 5

事不宜迟:

this.router.navigate(['..'], {relativeTo: this.activeRoute, skipLocationChange: true});
Run Code Online (Sandbox Code Playgroud)

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

  • 除了前面的注释之外,添加对“this.activeRoute”与什么相关的引用 (2认同)