代码之家  ›  专栏  ›  技术社区  ›  Markus sam

在子路由中设置命名路由器出口的内容

  •  5
  • Markus sam  · 技术社区  · 8 年前

    在我的应用程序中,我想在两个路由器出口中显示内容,一个是主出口,另一个是命名出口。如果我将两个出口都放在根级别,我可以如下设置命名出口的内容:

    this.router.navigate([{ outlets: { rootSecondary: ['rootSecondaryPath'] } }]);
    

    但是,我希望应用程序的总体布局能够提供单个路由器出口,并能够在子路由中使用不同的路由器出口结构。

    如果我创建一个子路由,该路由也有一个主出口和一个命名出口,我将无法设置辅助出口的内容。报告的错误为:

    无法匹配任何路由。

    这个 路线 定义如下:

    const appRoutes: Routes = [
      { path: '', component: RootPrimaryComponent },
      { path: 'rootSecondaryPath', component: RootSecondaryComponent, outlet: 'rootSecondary' },
      {
        path: 'child', component: ChildComponent, children:
          [
            { path: '', component: ChildPrimaryComponent },
            { path: 'childSecondaryPath', component: ChildSecondaryComponent, outlet: 'childSecondary' },
          ]
      },
    ];
    const appRouting = RouterModule.forRoot(appRoutes);
    

    的模板 应用程序。组成部分html 包含一个一次出口和一个命名的二次出口(出于测试目的):

    <router-outlet></router-outlet>
    <div style="border: solid 1px green">
      <router-outlet name="rootSecondary"></router-outlet>
    </div>
    

    上面的代码是通过按钮调用的,可以毫无问题地设置rootSecondary出口。

    模板 小孩组成部分html 定义放置在根主出口内部的两个出口:

    <router-outlet></router-outlet>
    <div style="border:solid 1px red">
      <router-outlet name="childSecondary"></router-outlet>
    </div>
    

    小孩主要的,重要的组成部分html 包含一个按钮,用于调用代码以设置辅助出口:

    <div>
      child-primary works!
      <button (click)="setChildSecondary()">Set child secondary</button>
    </div>
    

    单击后,将运行以下代码:

    setChildSecondary() {
      this.router.navigate([{ outlets: { childSecondary: ['childSecondaryPath'] } }]);
    }
    

    如何更改代码以填充路由器出口childSecondary?

    1 回复  |  直到 5 年前
        1
  •  6
  •   Markus sam    8 年前

    为了解决这个问题,我需要设置 relativeTo 当前活动路由的父级的参数:

    export class ChildPrimaryComponent {
    
      constructor(private readonly router: Router,
        private readonly route: ActivatedRoute) { }
    
      setChildSecondary() {
        this.router.navigate([{ outlets: { childSecondary: ['childSecondaryPath'] } }],
          { relativeTo: this.route.parent });
      }
    }