首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >子路由中指定路由器出口的设置内容

子路由中指定路由器出口的设置内容
EN

Stack Overflow用户
提问于 2017-12-08 20:06:44
回答 1查看 4.1K关注 0票数 5

在我的应用程序中,我想在两个路由器中显示内容,主路由器和命名路由器。如果将两个出口放置在根级别上,则可以像这样设置命名出口的内容:

代码语言:javascript
运行
复制
this.router.navigate([{ outlets: { rootSecondary: ['rootSecondaryPath'] } }]);

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

如果我创建了一个子路由,它也有一个主出口和一个命名的出口,那么我就无法设置次要出口的内容。报告的错误是:

无法匹配任何路线。

路由的定义如下:

代码语言:javascript
运行
复制
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);

app.component.html的模板包含一个主出口,并且--为了测试目的--一个命名的次要出口:

代码语言:javascript
运行
复制
<router-outlet></router-outlet>
<div style="border: solid 1px green">
  <router-outlet name="rootSecondary"></router-outlet>
</div>

上面的代码是从一个按钮调用,并设置rootSecondary出口没有任何问题。

模板child.component.html定义了放置在根主出口内部的两个出口:

代码语言:javascript
运行
复制
<router-outlet></router-outlet>
<div style="border:solid 1px red">
  <router-outlet name="childSecondary"></router-outlet>
</div>

child.primary.component.html包含一个按钮,该按钮调用代码以设置辅助出口:

代码语言:javascript
运行
复制
<div>
  child-primary works!
  <button (click)="setChildSecondary()">Set child secondary</button>
</div>

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

代码语言:javascript
运行
复制
setChildSecondary() {
  this.router.navigate([{ outlets: { childSecondary: ['childSecondaryPath'] } }]);
}

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-12-09 06:54:56

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

代码语言:javascript
运行
复制
export class ChildPrimaryComponent {

  constructor(private readonly router: Router,
    private readonly route: ActivatedRoute) { }

  setChildSecondary() {
    this.router.navigate([{ outlets: { childSecondary: ['childSecondaryPath'] } }],
      { relativeTo: this.route.parent });
  }
}
票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47721435

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档