[英]Ionic/Angular nested router-outlet: routerLinks only work once
我正在嘗試使用Angular 的路由指南在 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
)時,我可以單擊其中一個鏈接,然后在插座中呈現相應的子元素。 但是,當這種情況發生時, a
標簽上的href
(我假設 Angular 基於routerLink
將其放在那里)全部更改為導航到 URL。
因此,我無法在不重新加載頁面的情況下單擊其他組件鏈接來呈現該組件(返回到/home
)。
單擊鏈接之前(URL 為/home
):
單擊 Child A 鏈接后(URL 為/home/childa
):
Angular 文檔似乎沒有表明我的配置有任何錯誤,與英雄示例中的路由相比,我的代碼中看不到任何明顯不同的地方。 我究竟做錯了什么?
如果有幫助,這是我的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 {}
您必須將絕對路徑添加到您的RouterLink
指令:
<a [routerLink]="['/home', 'child-a']">Child A</a><br>
<a [routerLink]="['/home', 'child-b']">Child B</a><br>
讓我們首先了解RouterLink
(特別是RouterLinkWithRef
)指令的工作原理。 它將導航到的路線取決於當前激活的路線( ActivatedRoute
)。 當您使用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
被注入為ActivatedRoute
。
這就是問題發生的原因:當當前路由是/home
時,指令中注入的激活路由應該與/home/child-*
中的不同; 在這種情況下,它是相同的。
因此,當用戶第一次登陸/home
時,指令中注入的ActivatedRoute
將具有一定的值,我們稱之為X
。 但是當用戶訪問/home/child-a
時, router-outlet
外部的視圖保持不變, ActivatedRoute
的值也是如此。 這很重要,因為在處理絕對和相對路由路徑時(提供給路由器指令的任何沒有/
前綴的東西),Angular 將遍歷當前UrlTree
( UrlTree
= 作為字符串提供的路由路徑的反序列化版本) 並將嘗試用新零件替換舊零件。
用戶導航到/home/child-a
之后,那么在當前UrlTree
中就無法在指令中找到從當前ActivatedRoute
創建的舊部分,因為ActivatedRoute
不再與實際激活的路由對應,所以它已經過時了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.