如何在不同的URL上重复使用相同的组件实例 [英] How to reuse the same component instance on different urls
问题描述
上下文
我想创建一个地图组件,并希望在各种URL上重复使用.实例化该组件非常耗时,并且每次创建该组件时也会用尽图块请求来显示地图图像.
I want to create a map component, which I want to reuse on various URLs. Instantiating this component is a bit time consuming, and also uses up tile requests to display the map images everytime the component is created.
问题
当组件嵌套在树中时,如何在不同的URL上重复使用同一组件实例?
How can I reuse the same component instance on different urls when the component is nested in the tree?
在下面的堆叠闪电战中,每次我切换路线时都会实例化一个新的 ReusableComponent
On the stackblitz below, a new ReusableComponent
is instantiated every time I switch route
https://stackblitz.com/edit/angular-sr9stk?file = app%2Freusable.component.ts
注意
我了解 RouteReuseStrategy
,但这仅适用于顶级组件(即,路由设置中定义的组件)
I know about RouteReuseStrategy
, but this only works for top level components (i.e. the defined in routing setup)
使用5.2角
推荐答案
有种破解方法,但这是我使之正常工作的唯一方法
Kind of a hack but this was the only way I got it working
https://stackblitz.com/edit/angular-13dj9k
在服务中将Component创建为ComponentRef,然后将其插入指令的ViewContatiner中,该指令存在于每条路径上.hacky部分是我必须在导航之前监听NavigationStart事件以分离组件,以便可以将其重新连接到下一条路线上.
Creating the Component in a service as a ComponentRef then inserting it into a directive's ViewContatiner, the directive exists on each route. The hacky part was I had to listen the NavigationStart event to detach the component before the navigation so it could be reattached on the next route.
这篇关于如何在不同的URL上重复使用相同的组件实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!