简体   繁体   中英

Angular 2/4 : how to change route without recreating the component

I have several routes to the same component (namely /projects, /projects/create, /projects/:id and children, all pointing to my ProjectComponent). When navigating between /projects/:id with only :id changing everything is fine, I can subscribe to the params and update my content accordingly, but when I navigate from /projects to /projects/create or to /projects/:id, the component is recreated.

Is there any way to navigate to a route pointing to the same component without it being recreated ?

You should implement a custom RouteReuseStrategy

Create a service implementing the RouteReuseStrategy :

export class CustomReuseStrategy implements RouteReuseStrategy {

    handlers: {[key: string]: DetachedRouteHandle} = {};

    shouldDetach(route: ActivatedRouteSnapshot): boolean {
        return true;
    }

    store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle): void {
        this.handlers[route.routeConfig.path] = handle;
    }

    shouldAttach(route: ActivatedRouteSnapshot): boolean {
        return !!route.routeConfig && !!this.handlers[route.routeConfig.path];
    }

    retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle {
        if (!route.routeConfig) return null;
        return this.handlers[route.routeConfig.path];
    }

    shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
        return future.routeConfig === curr.routeConfig;
    }
}

And add this provider to the @NgModule :

providers: [
    {provide: RouteReuseStrategy, useClass: CustomReuseStrategy}
]

You can adjust the CustomReuseStrategy to only have certain paths where the component can be reused, but I'll leave that up to you to find out how.

source

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM