javascript / expert
Snippet
Custom Route Reuse Strategy for Domain-Specific Caching
RouteReuseStrategy allows fine-grained control over component destruction during navigation. By implementing this interface, you can cache entire component trees (DetachedRouteHandle) based on custom logic, such as route data flags, preventing re-initialization of complex views.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import { RouteReuseStrategy, ActivatedRouteSnapshot, DetachedRouteHandle } from '@angular/router';export class CustomCacheStrategy implements RouteReuseStrategy {private handles = new Map<string, DetachedRouteHandle>();shouldDetach(route: ActivatedRouteSnapshot): boolean {return route.data['keepAlive'] === true;}store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle): void {this.handles.set(route.routeConfig!.path!, handle);}shouldAttach(route: ActivatedRouteSnapshot): boolean {return !!this.handles.get(route.routeConfig!.path!);}retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle | null {return this.handles.get(route.routeConfig!.path!) || null;}shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {return future.routeConfig === curr.routeConfig;}}
angular
Breakdown
1
shouldDetach(route: ActivatedRouteSnapshot): boolean
Determines if a route should be stored for later use instead of being destroyed.
2
store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle)
Saves the detached component tree into a local cache (usually a Map).
3
shouldReuseRoute(future, curr)
Decides if the router should use the same component when moving between two routes.