【问题标题】:Angular routerLink with named outlet (angular 5.0.2)带有命名插座的角路由器链接(角5.0.2)
【发布时间】:2017-11-19 06:34:54
【问题描述】:

我已阅读有关此问题的所有帖子,但没有一篇适合我。

我有一个应用模块,一个路由模块,没有其他“模块”。我的发现是……

  1. 标准路由可以从任何组件链接到
  2. 具有命名出口的路由只能从默认应用组件链接到,而不能从其他组件链接到
  3. 使用 routerLink 从除应用程序组件以外的任何内容链接到命名插座会导致“错误:无法匹配任何路由。URL 段:”

我的路线是这样的……

{path: 'hellocontent', component: ContentHelloWorldComponentComponent,
pathMatch: 'full', outlet: 'helloc'},

routerLink 是...

<a [routerLink]="[{ outlets: { helloc: ['hellocontent'] } }]">action</a>.

我的路由器插座是...

<router-outlet name="helloc"></router-outlet>
<router-outlet></router-outlet>

该路由器链接在标准的 angular app.component.html 中完美运行,但在任何其他组件中都无法正常运行。它总是导致“错误:无法匹配任何路由。URL 段:”。

一旦我删除了命名的插座,并将 routerLink 更改为... &lt;a routerLink="hellocontent"&gt;action&lt;/a&gt; 在应用程序组件中,或&lt;a routerLink="/hellocontent"&gt;action&lt;/a&gt; 在另一个组件中,它可以完美地工作,但只能在主插座中。

因为它可能很重要,我链接的组件当然也定义在它们自己的路由中,例如...

{path: 'hello-world', component: HelloWorldComponentComponent}

这是预期的行为吗,命名的出口只能从定义它们的组件中访问?奇怪的是,我的大部分 html 包装器都在 app.component.html 中,但是除了主要出口之外的任何东西都不能在另一个组件中工作。

【问题讨论】:

    标签: angular


    【解决方案1】:

    我认为您对命名路由器插座感到困惑。 Router Outlet 位于任何组件的顶部,用于加载子组件。

    问题是当您将其放置在组件顶部然后尝试加载路径时,必须相应地更改定义的路径,它必须是 Route 参数而不是 Route,因为如果您将路径路径变为嵌套想要为组件子路由加载它使用子路由。

    Working Example

    对于子路由

    const routes: Routes = [
      { path: 'stuff', component: AComponent, children:[
        { path: ':index', component: BComponent},
        { path: ':index/edit', component: EditComponent, outlet:'editsection'}
      ]}
    ];
    
    <p>
      Detail section works! {{ index }}
     <button type="button"
       [routerLink]="['/stuff',{outlets:{editsection:':index/edit'}}]">Edit</button>
    </p>
    

    【讨论】:

    • 1.您的示例不包含子路由。我试过儿童路线,但它们不起作用。 2. 您的示例使用指令来包含 hello 组件,这使得 routerLink 工作,但我使用 routerLink 将 hello 组件加载到主路由器插座中。也许这就是它不起作用的原因,因为它现在超出了主页的范围。 3.我不知道如何设置在线示例,我会尽快看看是否可以,因为这可能会增加一些清晰度。
    • @TrentonD.Adams 是的,这不是我刚刚复制代码的原因。实际上我在我的 mobilr 上使用 SO,我已经从我的 git hub 复制并粘贴代码,并将其添加到 stackblitz。当我到达我的机器时会更新
    • 好的,这是我的意思的一个工作(非工作)示例。 stackblitz.com/edit/angular-vha6xw
    • 你有机会看一下这个例子吗?
    • @TrentonD.Adams 是的,当您加载子路线时,路线路径是绝对的,因为它应该是路线参数,您可以在将鼠标悬停在该链接上时检查
    猜你喜欢
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-06
    • 2019-10-23
    • 1970-01-01
    相关资源
    最近更新 更多