【问题标题】:Set up route to target the named <router-outlet> from component's template, not from AppComponent's template设置路由以从组件的模板而不是 AppComponent 的模板中定位命名的 <router-outlet>
【发布时间】:2018-11-24 16:22:33
【问题描述】:

动机

我的 Angular 应用程序中需要多个布局模板:一个用于身份验证相关组件的空模板、一个带有用于特定应用程序导航的菜单栏的模板以及一个向菜单栏添加侧边栏的模板。将侧边栏作为命名的路由器插座会很有帮助。

这是问题的演示/简化:假设TwoOutletsComponent有一个&lt;router-outlet name="seconde" /&gt;命名的路由器,我想要这个链接:/two/one(second:forsecond)来加载我的TwoOutletsComponent,在未命名的路由器中加载一些内容,然后加载/forsecond 在名为 router-outlet 的“第二个”中。激活该链接时,DOM 在逻辑上应该如下所示:

<AppComponent>
  <AppComponent's router-outlet>    
    <TwoOutletsComponent>
      <router-outlet named="sidebar>[content from /forsecond]</router-outlet>
      <router-outlet>[content from /two/one]</router-outlet>
    <TwoOutletsComponent>

鉴于上面的逻辑视图,我可以让/two/one 内容很好地加载到未命名的路由器插座中,但来自/forsecond 的内容不显示;控制台中未显示任何错误,启用路由器跟踪显示/forsecond 路由已正常解析。

另一方面,如果我将 &lt;router-outlet name="second" /&gt; 放入 AppComponent 中,那么 /forsecond 会加载得很好 - 只是不是我想要的!这种情况下的逻辑视图如下所示:

<AppComponent> / <-- this gets loaded by default
  <AppComponent's router-outlet>    
    <TwoOutletsComponent>
      <router-outlet>[content from /two/one]</router-outlet>
    <TwoOutletsComponent>
  <AppComponent's second router-outlet>[content from /foresecond]</router-outlet>

我的相关路线如下所示:

const routes: Routes = [
  { ... other routes not included },
  {
    path: "two", component: TwoOutletsComponent,
    children: [      
      { path: "one", component: PlainTextComponent }
    ]
  },
  { 
    path: "forsecond", 
    pathMatch: "full", 
    component: PlainTextComponent, 
    outlet: "second" 
  }
]

我认为正在发生的事情:

我认为 Angular 的路由器以上下文无关的方式处理所有路由,包括辅助路由。如果确实如此,那么在 AppComponent 的模板中寻找“第二个”路由器插座是有意义的。我希望以某种方式向路由器提示目标路由器出口将在 TwoOutletsComponent 的模板中找到,而不是在 AppComponent 的模板中。

在尝试提示路由器时,我尝试按顺序模仿用于主要内容的路由,但结果相同,没有显示内容:

我已经建立了一个 Stackblitz 希望能明确这一点: link to Stackblitz

【问题讨论】:

    标签: angular angular2-routing angular7 router-outlet


    【解决方案1】:

    我已经将此问题追踪到我认为 Angular 路由器找到命名出口的方式中的一个错误:即使是那些路由器也构造了一个具有当前视图的完整层次结构的树状结构,命名出口仅在 first 级别进行搜索。我认为这是一个错误,我认为路由器应该遵循“主要”出口并递归搜索正确命名的出口。

    我已经在 github 上提交了修复;如果它被接受(确认这确实是一个错误而不是“功能”),我将删除该问题。如果它没有被接受,我会保留这个问题(并修改这个答案)。

    https://github.com/angular/angular/pull/27262

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-12
      • 1970-01-01
      • 2017-09-17
      • 1970-01-01
      • 2016-06-01
      • 1970-01-01
      • 2019-09-02
      • 1970-01-01
      相关资源
      最近更新 更多