我正在尝试使用 Angular's routing guide 在 Angular Ionic v5 应用程序中实现一个简单的嵌套/子路由示例。 .我使用 ionic start
创建了一个项目并选择了 blank
模板,然后创建了两个组件 ChildAComponent
和 ChildBComponent
.这是来自 home.page.html
的相关代码片段:
<div id="container">
<strong>Ready to create an app?</strong>
<p>Start with Ionic <a target="_blank" rel="noopener noreferrer"
href="https://ionicframework.com/docs/components">UI Components</a></p>
<div id="stuff">
<a routerLink="child-a">Child A</a><br>
<a routerLink="child-b">Child B</a><br>
<a routerLink="404">404</a>
</div>
<div id="thing">
<router-outlet></router-outlet>
</div>
</div>
我正在尝试使用 a
标签来驱动什么组件在 router-outlet
中呈现.当我第一次加载页面(URL:/home
)时,我可以单击其中一个链接,相应的子元素会在导出中呈现。但是,当发生这种情况时,href
s 上 a
标签(我假设是基于 routerLink
s 由 Angular 放置的)全变到导航到的 URL。因此,我无法在不重新加载页面的情况下单击其他组件链接来呈现该组件(返回
/home
)。单击链接之前(URL 是
/home
):单击子 A 链接后(URL 为
/home/childa
):Angular 文档似乎没有表明我配置了任何错误,并且与 heroes example 中的路由相比,我在我的代码中看不到任何明显不同的内容。 .我究竟做错了什么?
这是我的
home-routing.module.ts
如果有帮助:import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomePage } from './home.page';
import { ChildAComponent } from './childa/childa.component';
import { ChildBComponent } from './childb/childb.component';
const routes: Routes = [
{
path: '',
component: HomePage,
children: [
{
path: 'child-a',
component: ChildAComponent,
},
{
path: 'child-b',
component: ChildBComponent,
},
]
}
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class HomePageRoutingModule {}
GitHub: https://github.com/zrev2220/router-link-bug
最佳答案
简答
您必须添加 绝对路径 给您的 RouterLink
指令:
<a [routerLink]="['/home', 'child-a']">Child A</a><br>
<a [routerLink]="['/home', 'child-b']">Child B</a><br>
详细解答
我们先来了解一下
RouterLink
(特别是 RouterLinkWithRef
)指令有效。它将导航到的路线取决于当前激活的路线( ActivatedRoute
)。这是what happens当您单击带有 RouterLinkWithRef
的元素时指令(例如 selector: 'a[routerLink]'
):/* ... */
this.router.navigateByUrl(this.urlTree, extras);
/* ... */
哪里this.urlTree
定义为 getter
:get urlTree(): UrlTree {
return this.router.createUrlTree(this.commands, {
relativeTo: this.route, // !
queryParams: this.queryParams,
fragment: this.fragment,
preserveQueryParams: attrBoolValue(this.preserve),
queryParamsHandling: this.queryParamsHandling,
preserveFragment: attrBoolValue(this.preserveFragment),
});
}
正如我们所见,有 relativeTo: this.route
, 其中 this.route
是 injected as ActivatedRoute
.这就是出现问题的原因:当当前路由为
/home
时,指令中注入(inject)的激活路由应该与来自/home/child-*
的路由不同。 ;在这种情况下,它是一样的。所以,当用户第一次登陆
/home
时, ActivatedRoute
在指令中注入(inject)会有一定的值,我们称之为X
.但是当用户去/home/child-a
,外景router-outlet
保持不变,ActivatedRoute
也是如此。的值(value)。这很重要,因为在处理绝对和相对路由路径时(提供给路由器指令的任何没有前缀 /
的内容),Angular 将遍历当前的 UrlTree
( UrlTree
= 作为字符串提供的路由路径的反序列化版本)并将尝试用新部分替换旧部分。用户导航到
/home/child-a
后,然后在当前 UrlTree
无法找到从当前 ActivatedRoute
创建的旧零件在指令中,因为 ActivatedRoute
不再与实际激活的路线对应,所以它已经过时了。
关于angular - ionic /Angular 嵌套路由器导出 : routerLinks only work once,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63417402/