【问题标题】:Angular 4 Router. Why "/path1/(<outlet-name>:'path2')" is a thing?Angular 4 路由器。为什么“/path1/(<outlet-name>:'path2')”是一个东西?
【发布时间】:2017-08-04 16:23:13
【问题描述】:

这种 URL “/services/55/(section:'data')” 是连接命名出口和路径的解决方法吗?我不明白为什么它们不能简单地成为“/services/55/data”,因为它的出口属性指定如下:

{
  path: 'services/:id',
  component: ServicesComponent,
  children: [
    {
      path: 'data',
      outlet: 'section',
      component: ServicesDataComponent
    }
  ]
}

【问题讨论】:

  • 您可以使用空路径来避免它。在这里看看这个答案,它是 angular 2 但应该是相同的。我正在使用没有辅助路径语法 stackoverflow.com/questions/45394728/… 的辅助路由器插座
  • 您的服务/:我将是无组件的。它的子“数据”将包含 ServicesComponent 和另一个子数组,该数组将包含您的路由器出口组件 ServicesDataComponent,其中包含空路径和出口名称。
  • @jmw5598 那些空的子路径解决了这一切。谢谢!还测试了兄弟姐妹和带有命名插座的嵌套空路由,它也可以工作。

标签: angular angular-router


【解决方案1】:

如果其他人遇到此问题,我会提供答案。要使用多个路由器插座并避免使用辅助路由器语法,您必须操纵您的路由。通常,您会为名为 router-outlet 的 aux 提供路由,如下面的配置。

普通命名路由器出口语法

{
  path: 'services/:id',
  component: ServicesComponent,
  children: [
    {
      path: 'data',
      outlet: 'section',
      component: ServicesDataComponent
    }
  ]
}

要导航到 about 路线,您可以使用 /services/55/(section:'data')。您可以通过嵌套子路由来避免这种情况

  1. 初始路径将是您的核心路径。在上面的例子中services/:id
  2. 然后,您将在此路径上声明包含所有子路径的子路径。这些子路径会将组件属性设置为包含名为 router-outlet 的 aux 的组件。
  3. 然后每个子路径将声明另一组子路径,其中包含一个空路径以及要在辅助路由器出口中加载的组件。

没有辅助路由器语法的新路由器配置

{
  path: 'services/:id',
  children: [
    {
      path: 'data',
      component: ServicesComponent,
      children: [
        {
          path: '',
          outlet: 'section',
          component: ServicesDataComponent
        }
      ]
    },
    {
      path: 'another',
      component: 'ServicesComponent',
      children: [
        {
          path: '',
          outlet: 'section',
          component: AnotherComponent
        }
      ]
    }
  ]
}

您的新路线将类似于 /services/55/data/services/55/another

通过使用空路径声明命名辅助路由器路由,您不再需要处理辅助名称路由器出口语法。

【讨论】:

  • component 属性是可选的,因此您可以省略 component: 'ServicesComponent'。事实上,typescript 会抛出错误Type 'string' is not assignable to type 'Type&lt;any&gt;
【解决方案2】:

您可以有多个命名的插座。 命名出口基本上是一个平行的子结构。
如果没有(),路由器将无法区分构成正常路由的部分和构成辅助路由的部分。

除了未命名的出口之外,您只需要并且只应该使用命名的出口。 例如,如果您有一个显示应用程序特定部分的路由(项目列表 > 项目),使用辅助路由,您可以在应用程序的侧面显示不同的菜单(在应用程序的列表 > 项目部分之外)

因此,在您的示例中,只需删除 outlet: 'section' andname="section"from`。

【讨论】:

    【解决方案3】:

    您正在使用命名RouterOutlets。引入了此功能,因此可以在单个页面或组件上拥有 多个 路由器出口。

    默认样式和约定是(当页面上没有多个路由器出口时)将路径作为单个组件,在单个未命名的路由器出口中,使用您描述的行为:

    {
      path: 'services/:id',
      component: ServicesComponent,
      children: [
        { path: 'data', component: ServicesDataComponent }
      ]
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多