Angular2:如何刷新与解析器相关的组件? [英] Angular2 : How to refresh resolver dependent components?
问题描述
我有三个组件,每个组件都有自己的解析器,可以从不同的API提取数据. 为此,这些组件依赖于URL,该URL通过服务在它们之间共享.
I have three components, each have their own resolver that fetch data from a different API. To do so, these components rely on an url, that is shared between them using a service.
我希望当对该URL进行更改时,每个组件都会重新加载自身,即重新启动解析器.
I want that when a change to that url happens, each components reloads itself, i.e to restart the resolvers.
我看了几个相关的SO问题,但没有提及使用解析器时的操作方法,请参阅:问题2 ,问题3
I had a look at several related S.O questions, but none mention how to do so when using resolvers, cf : question 1,question 2,question 3
我可以想到两种方式:
肮脏的方式:使用路由器重定向和空白组件强制刷新组件.
The dirty way : Force the refreshing of the component using a router redirect and a blank component.
this.router.navigateByUrl('blank',true);
this.router.navigateByUrl('home/(mapps:mobil//sw:simil//sf:sales)');
但这没用.有刷新,但是解析器没有...解析.
But that didn't work. There is a refresh, but the resolvers aren't...resolved.
另一种方式:使用BehaviorSubject或ChangeDetectorRef. 但是,对于如何实现它,我一无所知,考虑到检测到组件中的更改并不会真正帮助我重新启动解析器.
The other way : use a BehaviorSubject or a ChangeDetectorRef. But then, I am clueless as to how to achieve it, considering detecting changes within my components won't help me actually restart the resolvers.
我的感觉是必须以某种方式通过路由器完成此操作,因为这是有关解析器的知识:
My feeling is that this has to be done through the router somehow, because it is the one knowing about the resolvers :
const routes: Routes = [
{
path: '',
redirectTo: 'home',
pathMatch: 'full'
},
{
path: 'home',
component: HomeComponent,
children : [
{
path: '',
component: BlankComponent
},
{
path: 'simil',
component: SwComponent,
outlet: 'sw',
resolve: {
data: SwResolve
}
},
{
path: 'sales',
component: SalesComponent,
outlet: 'sf',
resolve: {
data: SalesResolve
}
}
]
},
{
path: 'blank',
component: BlankComponent
}
];
关于如何实现此目标的任何提示?
Any hints on how to achieved this ?
这是相关的插件
编辑6月17日: 不再需要空白组件的解决方法. 要刷新组件,只需回调路由:
Edit Jun 17 : There is no need for the blank component workaround anymore. To refresh components, simply call back the route :
this.router.navigateByUrl('home/(mapps:mobil//sw:simil//sf:sales)')
推荐答案
当前无法刷新路由.可能有可能做到在Angular 2.3中使用RouteReuseStrategy
.
It is not currently possible to refresh routes. It will probably be possible to do that with RouteReuseStrategy
in Angular 2.3.
解析器,并且可以从ActivatedRoute
中观察到.如果路线保持不变(未更改参数),则不会重新评估它们,因此应进行相应的设计.
Resolvers are reevaluated when a route changes and can be observed from ActivatedRoute
. They are not reevaluated if a route stays the same (no param is changed) and should be designed accordingly.
路由更改是异步的,解决方法是链接路由更改:
Route change is asynchronous, the workaround is to chain route changes:
this.router.navigateByUrl('blank').then(() => {
this.router.navigateByUrl('home/(mapps:mobil//sw:simil//sf:sales)');
})
这篇关于Angular2:如何刷新与解析器相关的组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!