Angular 2 新 (RC1) 路由器.嵌套路由 [英] Angular 2 new (RC1) router. Nested routes

查看:24
本文介绍了Angular 2 新 (RC1) 路由器.嵌套路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在子组件的 beta 版本中(比如 'child1'),您可以通过类似的方式告诉您的父组件加载(导航到)不同的子组件而不是当前组件:

In beta version from the child component (let's say 'child1') you could tell your parent to load (navigate to) a different child component instead of current by something like that:

 _router.parent.navigate(['child2']);

('_router' is injected in constructor)

在 RC1 中不再有父"属性,因此您似乎必须使用 _router.navigate() 并提供从应用根目录开始的完整 url.类似的东西

In RC1 there's no 'parent' property anymore so it seems like the you have to use _router.navigate() and provide the full url starting from the app root. Something like

/root/grandparent/parent/child2

现在,问题是如果子组件只知道父级的路由而不知道祖父级的路由——你怎么做?使用 _router.navigate(['../child2']) 会很好,但这给了我一个奇怪的错误,比如 "invalid number of '../'.

Now, the question is if the child component is only aware about parent's routes but not about grandparent - how do you do this? Would be nice to use _router.navigate(['../child2']) but that gives me a weird errors like "invalid number of '../'.

到目前为止我找到的获取父母网址的唯一方法是:

The only way to get parent's url I found so far is that:

_router.routeTree._root.children[0].value.stringifiedUrlSegments

(您也可以通过 OnActivate 事件到达那里)

(you can also get there from OnActivate event)

但这在我看来是错误的.它也可能因父母/祖父母的数量而异 - 我还没有尝试过.

but this looks just wrong to me. It also might differ depending on the number of parents/grandparents - I haven't tried yet.

那么,有没有更好的方法来做到这一点,或者相对路径应该有效而我做错了什么?

So, is there a better way to do that or relative path should work and I'm doing something wrong?

谢谢.

推荐答案

我遇到了同样的问题.就在今天,我找到了解决方案(它在 router.ts 文件中 此处 行:89)

I had the same problem. Just today I have found solution (it was in router.ts file here line:89)

/**
   * Navigate based on the provided array of commands and a starting point.
   * If no segment is provided, the navigation is absolute.
   *
   * ### Usage
   *
   * ```
   * router.navigate(['team', 33, 'team', '11], segment);
   * ```
   */
  navigate(commands: any[], segment?: RouteSegment): Promise<void> {
    return this._navigate(this.createUrlTree(commands, segment));
  }

您需要导入 RouteSegment 并将其添加到您的构造函数中

You need to import RouteSegment and add it you your constructor

import { Router, RouteSegment } from '@angular/router';
...
contructor(private $_router:Router, private $_segment:RouteSegment){}
...

//If you are in for example child1 and child 1 is sibling of child2
this.$_router.navigate(['../child2'],this.$_segment);

这篇关于Angular 2 新 (RC1) 路由器.嵌套路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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