2016-05-13 136 views
4

从子组件测试版(假设'child1'),你可以告诉你的父母通过类似的东西,而不是当前的负载(导航到)一个不同的子组件:Angular 2新(RC1)路由器。嵌套路线

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

('_router' is injected in constructor) 

在RC1没有'parent'property,所​​以它看起来像你必须使用_router.navigate(),并提供从应用程序根开始的完整url。像

/root/grandparent/parent/child2 

东西现在的问题是,如果子组件是只知道关于父母的路线,但不是祖父母 - 你怎么做到这一点? 将是不错的使用_router.navigate(['../child2'])但是,让我像"invalid number of '../'.

的唯一办法一个奇怪的错误,以得到父母的网址我迄今发现的是:

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

(你也可以从OnActivate事件到达那里)

但这看起来只是对我错了。它也可能根据父母/祖父母的数量而有所不同 - 我还没有尝试过。

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

谢谢。

回答

4

我有同样的问题。就在今天,我已经找到了解决方案(这是在router.ts文件here行: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); 
+0

WOW的人高超,你救我日:p感谢+1 –