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

标签 angular angular-routing angular-router

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

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

另一个问题是,如果有人想直接访问 URL,我想重定向到父“登录”路由。但我无法让它发挥作用。在我看来,这两个问题很相似。

知道怎么做吗?

最佳答案

你想要一个链接/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"

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

关于angular - 如何从子路由导航到父路由?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37196882/

相关文章:

Angular 8 : Why the component is not loading?

angular - 在 Angular 5 中,刷新当前路由会重定向到父路由

angularjs - Angular2 教程(英雄之旅): Cannot find module './app-routing.module'

Angular 2 loadChildren 不与 canActivateChild 一起工作

angular - ActivatedRoute 订阅第一个子参数观察者

javascript - 保留 Angular Router 查询参数有什么作用?

angular - Ionic 3 如何在点击事件中选择特定的 ionic 芯片?

angular - 使用 javascript 更改输入字段中的 ngModel 值的任何方法

angular - graphql Angular 突变在控制台中显示 "Error: Network error: Cannot read property ' 长度为 null"

angular - 如何在 Angular 中为路由参数指定类型