【发布时间】:2022-08-23 04:21:23
【问题描述】:
我正在研究一种可以在本地正常工作的自定义路由器重用策略,但是当我将其部署到 Vercel 或 Netlify 等服务时,应用程序路由不起作用。我单击路由器链接更改页面,但页面组件未正确加载,除非我重新加载。
路由器重用策略在应用模块上提供
imports: [BrowserModule, AppRoutingModule],
providers: [
{ provide: RouteReuseStrategy, useClass: CustomRouteReuseStrategy },
],
应用路由:
const routes: Routes = [
{
path: \'\',
pathMatch: \'full\',
component: Page1Component,
},
{
path: \'about\',
component: Page2Component,
},
{
path: \'test\',
children: [
{ path: \'\', component: Page3Component, pathMatch: \'full\' },
{ path: \'page4\', component: Page4Component },
{ path: \'page4/:id\', component: Page4Component },
{ path: \':id\', component: Page3Component },
],
},
{
path: \'**\',
redirectTo: \'\',
},
];
@NgModule({
declarations: [],
imports: [RouterModule.forRoot(routes, { onSameUrlNavigation: \'reload\' })],
exports: [RouterModule],
})
export class AppRoutingModule {}
链接:
<a routerLink=\"/\">home</a>
<a routerLink=\"/about\">about</a>
<a routerLink=\"/test\">test</a>
<a routerLink=\"/test/page4\">page 4</a>
自定义路由器重用
export class CustomRouteReuseStrategy implements RouteReuseStrategy {
private storedRoutes: { [key: string]: DetachedRouteHandle }[] = [];
shouldDetach(route: ActivatedRouteSnapshot): boolean {
return true;
}
store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle) {
const path = route.routeConfig.component.name;
const hasRoute = this.storedRoutes.some((i) => i[path]);
if (handle && !hasRoute) {
this.storedRoutes.push({ [path]: handle });
}
}
shouldAttach(route: ActivatedRouteSnapshot): boolean {
let path, isPathStored, remove;
if (route.children && !route.routeConfig?.component) {
return false;
}
path = route.routeConfig.component.name;
if (this.storedRoutes.length > 1) {
isPathStored = Object.keys(this.storedRoutes[0])[0] === path;
}
if (isPathStored) {
remove = this.storedRoutes.pop();
} else if (this.storedRoutes.length > 1) {
remove = this.storedRoutes.shift();
}
if (remove) {
this.deactivateOutlet(remove[Object.keys(remove)[0]]);
}
const hasRoute = this.storedRoutes.some((i) => i[path]);
return !!route.routeConfig && hasRoute;
}
retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle | null {
const path = route.routeConfig.component.name;
const index = this.storedRoutes.findIndex((i) => i[path]);
if (index > -1) {
return this.storedRoutes[index][path];
}
return null;
}
shouldReuseRoute(
future: ActivatedRouteSnapshot,
curr: ActivatedRouteSnapshot
): boolean {
return future.routeConfig === curr.routeConfig;
}
private deactivateOutlet(handle) {
const componentRef: ComponentRef<any> = handle.componentRef;
if (componentRef) {
componentRef.destroy();
}
}
}
标签: angular