【发布时间】:2018-10-02 22:48:37
【问题描述】:
我有一个应用程序,其中包含一些带有过滤器的页面,我想保留过滤器和结果,因此当我返回该页面时,它会显示这些过滤器和结果。所以我使用 ReuseStrategy 来保持某些组件的状态,但它不适用于延迟加载的子路由。当我沿着第一级路线导航时,它按预期工作,保持我想要的组件状态。但是,如果我导航到二级路由,然后访问另一条路由并返回其父路由,它会停止工作并抛出以下错误:无法重新附加从不同路由创建的 ActivatedRouteSnapshot。
这是我的 ReuseStrategy 类:
import { RouteReuseStrategy, ActivatedRouteSnapshot, DetachedRouteHandle } from '@angular/router';
interface RouteStorageObject {
snapshot: ActivatedRouteSnapshot;
handle: DetachedRouteHandle;
}
export class CustomReuseStrategy implements RouteReuseStrategy {
storedRoutes: { [key: string]: RouteStorageObject } = {};
private acceptedRoutes: string[] = [
'page1',
'page2',
'page3'
];
shouldDetach(route: ActivatedRouteSnapshot): boolean {
return this.acceptedRoutes.indexOf(route.data['key']) > -1;
}
store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle): void {
const storedRoute: RouteStorageObject = {
snapshot: route,
handle: handle
};
this.storedRoutes[route.data['key']] = storedRoute;
}
shouldAttach(route: ActivatedRouteSnapshot): boolean {
if (route.routeConfig.path === 'login') {
this.storedRoutes = {};
return false;
}
return !!route.data && !!this.storedRoutes[route.data['key']];
}
retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle {
if (!route.data || !this.storedRoutes[route.data['key']]) {
return null;
}
return this.storedRoutes[route.data['key']].handle;
}
shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
return future.routeConfig === curr.routeConfig;
}
}
我的 app-routing.module.ts:
...
export const routes: Routes = [
...
{ path: 'page1',
loadChildren: 'app/features/page1.module#Page1Module',
data: { key: 'page1' }
},
{
path: 'page2',
loadChildren: 'app/features/page2.module#Page2Module',
data: { key: 'page2' }
},
{ path: 'page3',
loadChildren: 'app/features/page3.module#Page3Module',
data: { key: 'page3' }
},
{ path: 'another-page',
loadChildren: 'app/features/another-page.module#AnotherPageModule',
data: { key: 'another-page' }
},
{ path: 'home', redirectTo: 'page1', pathMatch: 'full' },
{ path: '**', redirectTo: 'page1', pathMatch: 'full' }
];
...
还有page1-routing.module.ts(page1有子页面):
...
const routes: Routes = [
{ path: '', component: Page1Component },
{
path: 'page1-1',
loadChildren: './page1-1/page1-1.module#Page11Module',
data: { key: 'page1-1' }
},
{
path: 'page1-2',
loadChildren: './page1-2/page1-2.module#Page12Module',
data: { key: 'page1-2' }
},
];
...
我有以下页面:
- 第 1 页 (保持状态)
- 1-1页
- 第1-2页
- 第 2 页 (保持状态)
- 第 3 页 (保持状态)
- 另一页
正确导航示例(不会引发任何错误):第 1 页 => 第 1-1 页 => 第 1 页 => 第 2 页 => 第 1 页
错误导航示例(抛出错误无法重新附加从不同路线创建的ActivatedRouteSnapshot):第1页=>第1-1页=>第2页=>第1页
【问题讨论】:
标签: angular