目前有AAA.BBB.CCC三種業務
想說在CCC的頁面底下加上可以前往C01和C02的第二層NavBar
所以
最上方的Navigation Bar是這樣
<mat-toolbar class="" >
<div class="" >
<button mat-button [routerLink]="['/AAA']" routerLinkActive="activebutton">
AAA
</button>
</div>
<div class="">
<button
mat-button
[routerLink]="['/BBB']" routerLinkActive="activebutton" >
BBB
</button>
</div>
<div class="">
<button
mat-button
[routerLink]="['/CCC']" routerLinkActive="activebutton" >
CCC
</button>
</div>
<button mat-button [routerLink]="['/login']">登出</button>
</mat-toolbar>
<router-outlet></router-outlet>
然後路徑規劃如下
const routes: Routes = [
{
path: '',
canActivate: [AuthGuard],
component: LayoutComponent,
children: [
{ path: '', redirectTo: 'AAA', pathMatch: 'full' },
{ path: 'AAA', component: AAAComponent },
{ path: 'BBB', component: BBBPageComponent },
{
path: 'CCC',
component: CCCComponent,
children: [
{
path: 'C01',
component: C01Component,
},
{
path: 'C02',
component: C02Component,
},
],
},
],
},
{ path: 'login', component: LoginComponent },
{
path: '**',
redirectTo: 'login',
pathMatch: 'full',
},
];
然後CCC的Navigation Bar是這樣設定
<mat-toolbar>
<div class="">
<button
mat-button
[routerLink]="['/CCC/C01']"
routerLinkActive="activebutton"
>
C01
</button>
</div>
<div class="">
<button
mat-button
[routerLink]="['/CCC/C02']"
routerLinkActive="activebutton"
>
C02
</button>
</div>
</mat-toolbar>
<router-outlet></router-outlet>
第一次進入CCC會顯示點選C01和C02的按鈕
C01和C02頁面都很正常也能切換
但是當去點BBB或AAA之後
再回來點CCC,就會跳以下錯誤
ERROR Error: Uncaught (in promise):
Error: Cannot reattach ActivatedRouteSnapshot created from a different route
有採用RouteReuseStrategy
import {
RouteReuseStrategy,
DefaultUrlSerializer,
ActivatedRouteSnapshot,
DetachedRouteHandle,
} from '@angular/router';
interface RouteStorageObject {
snapshot: ActivatedRouteSnapshot;
handle: DetachedRouteHandle;
}
export class AppRoutingCache implements RouteReuseStrategy {
public static handlers: { [key: string]: DetachedRouteHandle } = {};
// 判斷路由是否能重複使用
public shouldDetach(route: ActivatedRouteSnapshot): boolean {
if (!route.routeConfig || route.routeConfig.loadChildren) {
return false;
}
// 默認所有的路由設定都可以重複使用
// 可透過 route.data 的方式來設定重複使用的規則
return true;
}
// 當路由離開時,會觸發此方法
public store(
route: ActivatedRouteSnapshot,
handle: DetachedRouteHandle,
): void {
// 將目前路由內容暫存起來
AppRoutingCache.handlers[route.routeConfig.path] = handle;
}
// 當路由進入時,可判斷是否還原路由的暫存內容
public shouldAttach(route: ActivatedRouteSnapshot): boolean {
return (
!!route.routeConfig && !!AppRoutingCache.handlers[route.routeConfig.path]
);
}
// 從 Cache 中取得對應的暫存內容
public retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle {
if (!route.routeConfig) {
return null;
}
if (route.routeConfig.loadChildren) {
return null;
}
return AppRoutingCache.handlers[route.routeConfig.path];
}
// 判斷是否同一路由
public shouldReuseRoute(
future: ActivatedRouteSnapshot,
current: ActivatedRouteSnapshot,
): boolean {
return future.routeConfig === current.routeConfig;
}
}
有找到這幾篇
但是改了還是一樣
不知道是眼睛太大還是哪邊我概念有問題…
求幫忙診斷…感謝