当用户使用“路由器重用策略”关闭/刷新选项卡或(单击“后退/向前”)时,我正在尝试保留组件数据,但是在添加CustomReuseStrategy提供程序routerLink后,该链接正常停止工作。
登录后,我们将重定向到“ / dashboard / begin”,然后如果我尝试通过routerLink进入“ / dashboard / search”或“ / dashboard / 123”,则组件不会更改
但是,直接访问网址效果很好
有人经历过吗?
app.module.ts
@NgModule({
providers: [
AuthGuard,
{
provide: RouteReuseStrategy,
useClass: CustomReuseStrategy
}]
})
app.routing.ts
const ROUTES: Routes = [
{ path: 'dashboard', loadChildren: './dashboard/dashboard.module#DashboardModule', canActivateChild: [AuthGuard]},
{ path: 'login', component: LoginComponent },
{ path: '', redirectTo: '/login', pathMatch: 'full' }
]
dashboard.routing.ts
const DASHBOARD_ROUTES: Routes = [
{
path: '', component: DashboardComponent,
children: [
{
path: 'begin',
component: BeginListComponent,
},
{
path: 'search',
children: [
{path: '', component: SearchListComponent },
{path: ':id', component: SearchIdComponent}
]
}
}
]
custom.reuse.strategy.ts
import { ActivatedRouteSnapshot, DetachedRouteHandle, RouteReuseStrategy } from '@angular/router';
export class CustomReuseStrategy implements RouteReuseStrategy {
public static handlers: { [key: string]: DetachedRouteHandle } = {};
private static waitDelete: string;
public static deleteRouteSnapshots(): void {
CustomReuseStrategy.handlers = {};
}
public static deleteRouteSnapshot(name: string): void {
if (CustomReuseStrategy.handlers[name]) {
delete CustomReuseStrategy.handlers[name];
} else {
CustomReuseStrategy.waitDelete = name;
}
}
public shouldDetach(route: ActivatedRouteSnapshot): boolean {
console.log(route);
if (!route) {
CustomReuseStrategy.deleteRouteSnapshots();
return false;
}
if (route.params && Object.keys(route.params).length > 0) {
return false;
}
return true;
}
public store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle): void {
if (
CustomReuseStrategy.waitDelete &&
CustomReuseStrategy.waitDelete === this.getRouteUrl(route)
) {
CustomReuseStrategy.waitDelete = null;
return;
}
CustomReuseStrategy.handlers[this.getRouteUrl(route)] = handle;
}
public shouldAttach(route: ActivatedRouteSnapshot): boolean {
return !!CustomReuseStrategy.handlers[this.getRouteUrl(route)];
}
public retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle {
if (!route.routeConfig) {
return null;
}
return CustomReuseStrategy.handlers[this.getRouteUrl(route)];
}
public shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
return (
future.routeConfig === curr.routeConfig &&
JSON.stringify(future.params) === JSON.stringify(curr.params)
);
}
private getRouteUrl(route: ActivatedRouteSnapshot) {
return route['_routerState'].url.replace(/\//g, '_');
}
}