【问题标题】:Angular 2 new (RC1) router. Nested routesAngular 2 新 (RC1) 路由器。嵌套路由
【发布时间】:2016-09-09 00:24:55
【问题描述】:

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

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

('_router' is injected in constructor)

在 RC1 中不再存在“父”属性,因此您似乎必须使用 _router.navigate() 并提供从应用根目录开始的完整 url。像

/root/grandparent/parent/child2

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

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

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

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

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

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

谢谢。

【问题讨论】:

    标签: angular angular2-routing


    【解决方案1】:

    我遇到了同样的问题。就在今天我找到了解决方案(它在 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);
    

    【讨论】:

      猜你喜欢
      • 2016-09-20
      • 2016-09-20
      • 2015-08-01
      • 1970-01-01
      • 2016-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多