使用Angular2+路由重用策略后,如何调用一个方法返回缓存组件来更新部分



我有一个列表页面,点击一列进入详情页面。编辑并返回。因为使用RouteReuseStrategy,它可以保持场景的列表页保持不变。但我想部分更新,但是,我不知道如何触发它。

这是我的RouteReuseStrategy服务,大部分都是相同的。

export class SimpleReuseStrategy implements RouteReuseStrategy {
_cacheRouters: { [key: string]: any } = {};
shouldDetach(route: ActivatedRouteSnapshot): boolean {
    return true;
}
store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle): void {
    this._cacheRouters[route.routeConfig.path] = {
        snapshot: route,
        handle: handle
    };
}
shouldAttach(route: ActivatedRouteSnapshot): boolean {
    return !!this._cacheRouters[route.routeConfig.path];
}
retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle {
    return this._cacheRouters[route.routeConfig.path].handle;
}
shouldReuseRoute(future: ActivatedRouteSnapshot, curr: 
ActivatedRouteSnapshot): boolean {
    return future.routeConfig === curr.routeConfig;
}
}

在列表页面组件中,您可以侦听路由更改:

  • 检测导航开始是否来自详细路线,即/detail/1
    • 如果是这样,则获取路由的"id"参数/detail/1
    • 替换列表中的该元素

// List component
ngOnInit(): void {
 this.subscription = this.router.events.subscribe((event) => {
  if (event instanceof NavigationStart) {
      // checkIfDetailPage and store ID
  }
  if (event instanceof NavigationEnd) {
      // checkIfThisPage and get the ID
      // replace element with ID
  }
});
}

检测更改的替代方法(而不是观察路由更改),您可以实现列表组件订阅和详细信息组件通知的服务。

最新更新