Reputation: 373
In my application there are three components. 1) Map 2) Search 3) User Profile
After login by default I load MAP component then I can go any other screen using header menu link.
I want to achieve functionality like once I load the map component in the browser it shouldn't reload component again when I come back to map screen from other screen or back button. Because when I come back from other screen it's reloading all pushpin and related data and reset the user's last view on map.
Note - In map component I load map on ngOnIt event.
How can I achieve this functionality in Angular 2/4 ?
Sample screenshot it attached for reference.
Upvotes: 3
Views: 4236
Reputation: 373
This is how I achieved this.
First - Implemented RouteReuseStrategy interface.
import {RouteReuseStrategy, ActivatedRouteSnapshot, DetachedRouteHandle} from '@angular/router';
export class CustomReuseStrategy implements RouteReuseStrategy {
handlers: {[key: string]: DetachedRouteHandle} = {};
shouldDetach(route: ActivatedRouteSnapshot): boolean {
//console.debug('CustomReuseStrategy:shouldDetach', route);
return !!route.data && !!(route.data as any).shouldDetach;
}
store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle): void {
//console.debug('CustomReuseStrategy:store', route, handle);
this.handlers[route.routeConfig.path] = handle;
}
shouldAttach(route: ActivatedRouteSnapshot): boolean {
//console.debug('CustomReuseStrategy:shouldAttach', route);
return !!route.routeConfig && !!this.handlers[route.routeConfig.path];
}
retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle {
//console.debug('CustomReuseStrategy:retrieve', route);
if (!route.routeConfig) { return null; }
return this.handlers[route.routeConfig.path];
}
shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
//console.debug('CustomReuseStrategy:shouldReuseRoute', future, curr);
return future.routeConfig === curr.routeConfig;
}
}
Second - added CustomReuseStrategy provider in the app.module.
import {RouteReuseStrategy} from '@angular/router';
import {CustomReuseStrategy} from './Shared/reuse-strategy';
providers: [
{ provide: RouteReuseStrategy, useClass: CustomReuseStrategy }
]
Third - added shouldDetach attribute in app.routing.ts
import { Routes, RouterModule } from "@angular/router";
import { MapComponent } from './components/map/map.component';
const ROUTES: Routes = [
{ path: 'maps', component: MapComponent , canActivate:[AuthGuard], data: { shouldDetach: true} },
];
Upvotes: 3