在子组件的 beta 版本中(比方说 'child1'
),您可以告诉您的父组件加载(导航到)一个不同的子组件而不是当前的子组件:
_router.parent.navigate(['child2']);
('_router' is injected in constructor)
在 RC1 中,不再有“parent”属性,因此您似乎必须使用 _router.navigate()
并提供从应用根目录开始的完整 url。有点像
/root/grandparent/parent/child2
现在,问题是子组件是否只知道父组件的路由而不知道祖父组件的路由 - 你如何做到这一点?
使用 _router.navigate(['../child2'])
会很好,但这给了我一个奇怪的错误,比如 "invalid number of '../'.
到目前为止,我找到的获取 parent url 的唯一方法是:
_router.routeTree._root.children[0].value.stringifiedUrlSegments
(您也可以从 OnActivate 事件到达那里)
但这对我来说是错误的。它也可能因 parent /祖 parent 的数量而有所不同 - 我还没有尝试过。
那么,是否有更好的方法来做到这一点,或者相对路径应该有效,但我做错了什么?
谢谢。
最佳答案
我遇到了同样的问题。就在今天,我找到了解决方案(在 router.ts 文件 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 并将其添加到您的构造函数中
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) 路由器。嵌套路线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37199272/