问题
In the new Angular 2 router, they have removed the CanReuse interface. Is there a way to achieve this functionality (force component reload) with another feature of the router?
回答1:
Now there's RouteReuseReuse strategy, which you can replace with your own, if you want to re-render the route on navigation, you can do it like this
1.Define Custom Strategy (this strategy works just like the old-router)
export class CustomReuseStrategy implements RouteReuseStrategy {
shouldDetach(route: ActivatedRouteSnapshot): boolean { return false; }
store(route: ActivatedRouteSnapshot, detachedTree: DetachedRouteHandle): void {}
shouldAttach(route: ActivatedRouteSnapshot): boolean { return false; }
retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle { return null; }
shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
if(future.routeConfig !== curr.routeConfig) {
return false;
} else if(Object.keys(future.params).length !== Object.keys(curr.params).length ||
Object.keys(future.queryParams).length !== Object.keys(curr.queryParams).length) {
return false;
} else {
return Object.keys(future.params).every(k => future.params[k] === curr.params[k]) &&
Object.keys(future.queryParams).every(k => future.queryParams[k] === curr.queryParams[k]);
}
}
}
2.Override/Provide Custom Strategy
NgModule({
imports: [...]
declarations: [...],
providers: [
{provide: RouteReuseStrategy, useClass: CustomReuseStrategy}
]
)}
export class AppModule {
}
回答2:
i had the same problem (components getting reused instead of new created).
because there is nothing included in the current angular 2 Version, i have a working Workaround.
In my case I want to destroy the outlet-component when my modal window closes.
$('#mymodal_window').on("hide.bs.modal", ()=>{
//destroy manually
for(var o of this.route.parent.children){
if(o.outlet=="myoutletname")
{
var s:any = o.snapshot;
s._routeConfig = null;
}
}
});
internally angular checks if the snapshots (it only compares the _routeConfig) are equal and will reuse the component. In my Workaround i simply delete the _routeConfig on window-close and the next time it will create a new instance of the component.
来源:https://stackoverflow.com/questions/37353503/angular-2-new-router-routercanreuse