angular中,不同路由不同页面跳转时,原页面直接销毁,不做任何处理处理Page,如果页面没有被销毁,一定是路由复用。如下图所示,在不采用路由复用策略的情况下,可以看到切换页面时会直接销毁原页面。采用路由复用策略后,可以看到跳转后,原来的页面并没有被破坏。怎么做其实很简单。Angular原生提供了路由相关的接口。先新建一个ts文件然后继承angular提供的路由策略接口修改接口。代码如下handle:DetachedRouteHandle;}exportclassRouterStrategy实现RouteReuseStrategy{storedRoutes:{[key:string]:RouterStroageObject}={};storedData:{[key:string]:any}={};/****路由离开时是否保存页面,这是实现自定义路由复用策略最重要的方式。其中:当返回值为true时,路由离开时保存页面信息,再次激活路由时直接显示保存的页面。当返回值为false时,路由离开时直接销毁组件,再次激活路由时直接初始化到新页面。*/shouldDetach(route:ActivatedRouteSnapshot):boolean{//console.log('routeintheeventof'shouldDetach',route)if(route.data.noReuse){returnfalse}returntrue}/**如果shouldDetach方法返回true,将调用此方法来保存页面。*/store(route:ActivatedRouteSnapshot,handle:DetachedRouteHandle):void{//console.log('storeevent','route',route,'handle',handle);conststoredRoute:RouterStroageObject={snapshot:route,handle:handle}this.storedRoutes[this.getRouteUrl(route)]=storedRoute;//console.log('this.storedRoutes',this.storedRoutes)}/***路由进入页面时是否有可以复用的页面。true:重用页面,false:生成新页面*//***routeactivation获取保存的页面,如果返回null,则生成一个新页面*/retrieve(route:ActivatedRouteSnapshot):DetachedRouteHandle|null{if(!route.routeConfig||route.routeConfig.loadChildren||!this.storedRoutes[this.getRouteUrl(route)]){returnnull}returnthis.storedRoutes[this.getRouteUrl(route)].handle}/***判断跳转前的路由页面是否可以在跳转后使用,即跳转前后使用同一个页面*/shouldReuseRoute(future:ActivatedRouteSnapshot,curr:ActivatedRouteSnapshot):boolean{returnfuture.routeConfig===curr.routeConfig&&JSON.stringify(future.params)===JSON.stringify(curr.params);}privategetRouteUrl(route:ActivatedRouteSnapshot){//@ts-ignoreconsturl=route['_routerState'].url;常量路径=url.replace(/\//g,'_')+'_'+(route.routeConfig?.loadChildren||route.routeConfig?.component?.toString().split('(')[0].split('')[1]);returnpath}}保存后,在要使用的路由文件中引入import{NgModule}from'@angular/core';import{RouteReuseStrategy,RouterModule,Routes}from'@angular/router';从'./routerStrategy'导入{RouterStrategy};从'./test1-component/test1-component.component'导入{Test1ComponentComponent};从'./test2-component/test2-component.component'导入{Test2ComponentComponent};constroutes:Routes=[{path:'',pathMatch:'full',redirectTo:'/test1'},{path:'test1',component:Test1ComponentComponent,data:{noReuse:false}},{path:'}test2',component:Test2ComponentComponent},];@NgModule({imports:[RouterModule.forRoot(routes)],exports:[RouterModule],providers:[{provide:RouteReuseStrategy,useClass:RouterStrategy}]})exportclassAppRoutingModule{}如果我将noReuse的值更改为true,那么Test1页面将被销毁跳转后yed,如果设置为false或者不设置,则跳转后不会销毁破坏
