Angular2:如何刷新解析器相关组件? [英] Angular2 : How to refresh resolver dependent components?
问题描述
我有三个组件,每个组件都有自己的解析器,可以从不同的 API 获取数据.为此,这些组件依赖于使用服务在它们之间共享的 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 问题,但没有提到在使用解析器时如何操作,参见:问题 1,问题 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屋!