如何从子路由导航到父路由? [英] How do I navigate to a parent route from a child route?

查看:52
本文介绍了如何从子路由导航到父路由?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题很经典.我有一个应用程序的私有部分,它位于 登录表单 后面.登录成功后,进入管理应用的子路由.

My problem is quite classic. I have a private part of an application which is behind a login form. When the login is successful, it goes to a child route for the admin application.

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

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,我想重定向到父登录"路由.但我不能让它工作.在我看来,这两个问题是相似的.

Another problem is that if someone want to access the URL directly, I want to redirect to the parent "login" route. But I can't make it work. It seems to me like theses two issues are similar.

知道怎么做吗?

推荐答案

您想要链接/HTML 还是命令式/在代码中路由?

Do you want a link/HTML or do you want to route imperatively/in code?

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

Link: The RouterLink directive always treats the provided link as a delta to the current 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 数组:

With RouterLink, remember to import and use the directives array:

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

命令式:navigate() 方法需要一个起点(即,relativeTo 参数).如果没有提供,导航是绝对的:

Imperative: The navigate() method requires a starting point (i.e., the relativeTo parameter). If none is provided, the navigation is absolute:

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

这篇关于如何从子路由导航到父路由?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆