Angular 2 new router routerCanReuse

懵懂的女人 提交于 2020-01-02 07:27:28

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!