具名插座的 Angular routerLink(Angular 5.0.2)

7

我已经阅读了所有关于此问题的帖子,但是没有一篇对我有用。

我有一个应用程序模块和一个路由模块,没有其他“模块”。 我发现以下情况:

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

我的路由如下...

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

The routerLink is...

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

我的路由器插座...

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

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

只要我删除了命名出口,并将routerLink更改为...<a routerLink="hellocontent">action</a> 在app组件中,或者在另一个组件中 <a routerLink="/hellocontent">action</a>,它就可以完美地工作,但仅适用于主出口。

由于这可能很重要,因此我从中链接的组件当然也在其自己的路由中定义,例如...

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

这是预期的行为吗?即仅能从定义它们的组件中访问命名出口?很奇怪,因为我的大部分html包装器都在app.component.html中,但除了主要出口之外,其他任何出口都无法从另一个组件中使用。

1个回答

2

我认为你对命名路由出口感到困惑。路由器出口位于任何组件的顶部,用于加载子组件。

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

工作示例

对于子路由

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组件加载到主要的router-outlet中。也许这就是为什么它不起作用的原因,因为它现在已经超出了主页面的范围。
  3. 我不知道如何设置在线示例,我会尽快看看是否可以做到,因为这可能会增加一些清晰度。
- Trenton D. Adams
@TrentonD.Adams 是的,这就是我只是复制了代码的原因。实际上,我正在我的手机上使用 SO,并从我的 git hub 复制和粘贴代码,也将其添加到 stackblitz 中。等我回到机器上后会更新。 - Rahul Singh
好的,这里有一个可以(不能)工作的例子,展示了我的意思。https://stackblitz.com/edit/angular-vha6xw - Trenton D. Adams
这对我来说毫无意义。:( 我不创建子路由。 子路由是不是与子元素有所不同? - Trenton D. Adams
访问有关路由的工作示例时出现了路由问题。 - Shadi Alnamrouti
显示剩余4条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接