Reputation: 21
I want to create a custom RouteReuseStrategy. The purpose of this RouteReuseStrategy is to store the parent route when navigating from a parent to a child route.
Routes:
export const routes: Routes = [
{
path: "",
component: DashboardComponent,
canActivate: [ dashboardAuthGuard ],
children: [
{
path: "app",
providers: [ ModalService ],
children: [
{
path: "sale",
loadChildren: () => import("./dashboard/suffapps/sale/sale.module").then(module => module.SaleModule)
},
{
path: "reports",
loadChildren: () => import("./dashboard/suffapps/reports/reports.module").then(module => module.ReportsModule)
}
]
}
]
},
{
path: "login",
loadComponent: () => import("./login/login.component").then(component => component.LoginComponent)
}
];
Routing modules in app routes:
const routes: Routes = [
{
path: "",
component: SuffappComponent,
canActivate: [ saleActivateGuard ],
canDeactivate: [ suffappDeactivateGuard, saleDeactivateGuard ],
children: [
{
path: "",
component: SuffappSaleComponent,
resolve: {
resolver: saleResolver
}
},
{
path: "case",
component: SuffappSaleCaseComponent,
canActivate: [ caseActivateGuard ],
resolve: {
resolver: saleCaseResolver
}
}
]
},
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule],
})
export class SaleRoutingModule { }
When going from /app/sale
route to /app/sale/case
route, I want to store /app/sale
route.
I've read documentation and watched videos about RouteReuseStrategies but I don't know how to do it.
import { ActivatedRouteSnapshot, DetachedRouteHandle, RouteReuseStrategy } from "@angular/router";
export class CustomRouteReuseStrategy implements RouteReuseStrategy {
stored: { route: ActivatedRouteSnapshot, handle: DetachedRouteHandle } | null = null
shouldDetach(route: ActivatedRouteSnapshot): boolean {
console.log("shouldDetach", route.data["reuse"]);
return route.data["reuse"]
}
store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle | null): void {
console.log("store", route, handle);
this.stored = { route, handle: handle! }
}
shouldAttach(route: ActivatedRouteSnapshot): boolean {
console.log("shouldAttach", this.stored?.route.routeConfig == route.routeConfig);
return this.stored?.route.routeConfig == route.routeConfig;
}
retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle | null {
console.log("retrieve", this.stored?.handle || null);
return this.stored?.handle || null;
}
shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
console.log("shouldReuseRoute", future.routeConfig === curr.routeConfig);
return future.routeConfig === curr.routeConfig;
}
}
I write this code.
This code stores the /app/sale
route when going from /app/sale
to /app/sale/case
.
But there is a problem:
It also stores when going from /app/sale
to /app/reports
.
Upvotes: 1
Views: 70