感谢@Günter Zöchbauer 提供的示例,出于我自己的理解,我决定提炼一个最小的示例。
看到它在行动
总之:
首先我实现了一个RouteReuseStrategy:
export class CustomReuseStrategy implements RouteReuseStrategy {
handlers: {[key: string]: DetachedRouteHandle} = {};
calcKey(route: ActivatedRouteSnapshot) {
let next = route;
let url = '';
while(next) {
if (next.url) {
url = next.url.join('/');
}
next = next.firstChild;
}
return url;
}
shouldDetach(route: ActivatedRouteSnapshot): boolean {
return true;
}
store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle): void {
this.handlers[this.calcKey(route)] = handle;
}
shouldAttach(route: ActivatedRouteSnapshot): boolean {
return !!route.routeConfig && !!this.handlers[this.calcKey(route)];
}
retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle {
if (!route.routeConfig) { return null; }
return this.handlers[this.calcKey(route)];
}
shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
return this.calcKey(curr) === this.calcKey(future);
}
}
在我的AppModule
中,我添加了一个新的提供者并配置了一些路由:
export const ROUTES: Routes = [
{
path: 'one',
component: OneComponent
},
{
path: 'two',
component: TwoComponent
},
];
@NgModule({
...
imports: [... RouterModule.forRoot(ROUTES)...]
providers: [...{ provide: RouteReuseStrategy, useClass: CustomReuseStrategy }...],
...
})
export class AppModule { }
最后,我定义了一些组件如下:
@Component({
selector: 'my-app',
template: `
<a [routerLink]="['/one']" >Route One</a><br>
<a [routerLink]="['/two']" >Route Two</a><br>
<router-outlet></router-outlet>
`
})
export class AppComponent {}
@Component({
selector: 'app-one',
template: `
Route One currently showing<br>
<input type="text" placeholder="enter some text">
`,
})
export class OneComponent {}
@Component({
selector: 'app-two',
template: `
Route Two currently showing<br>
<input type="text" placeholder="enter some text">
`,
})
export class TwoComponent {}