Angular 2新路由器router可以重复使用 [英] Angular 2 new router routerCanReuse

查看:101
本文介绍了Angular 2新路由器router可以重复使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在新的Angular 2路由器中,他们删除了CanReuse接口.是否可以通过路由器的另一功能来实现此功能(强制重新加载组件)?

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?

推荐答案

现在有 RouteReuseReuse 策略,您可以将其替换为自己的策略,如果要在导航中重新渲染该路线,则可以这样做

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.定义自定义策略(此策略的工作方式与旧路由器一样)

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.覆盖/提供自定义策略

NgModule({
    imports: [...]
    declarations: [...],
    providers: [
        {provide: RouteReuseStrategy, useClass: CustomReuseStrategy}
    ]
)}
export class AppModule {
}

这篇关于Angular 2新路由器router可以重复使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆