导航到同一路线不刷新组件? [英] Navigating to the same route not refreshing the component?
问题描述
我已升级为使用路由器已弃用的新 Angular 2 路由器,并且某些行为发生了变化.
I've upgraded to use the new Angular 2 router from router-deprecated and some behavior has changed.
我遇到问题的页面是搜索页面.我们选择使用 HashLocationStrategy
将所有搜索词放在 URL 中.路线如下所示:
The page I'm having issues with is a search page. We've chosen to put all the search terms in the URL using the HashLocationStrategy
. The routes look like this:
const routes: RouterConfig = [
{ path: '', component: HomeComponent },
{ path: 'search/:term/:cat/:page/:sort/:size/:more', component: HomeComponent },
{ path: 'search/:term/:cat/:page/:sort/:size', component: HomeComponent },
{ path: 'search/:term/:cat/:page/:sort', component: HomeComponent },
{ path: 'search/:term/:cat/:page', component: HomeComponent },
{ path: 'search/:term/:cat', component: HomeComponent },
{ path: 'search/:term', component: HomeComponent },
{ path: 'details/:accountNumber', component: DetailsComponent }
];
我知道查询字符串方法可能更适合所有这些选项,但项目要求由其他人决定...
I know a query string approach might be better fit for all these options but project requirements decided by other people...
无论如何,如果我使用 this.router.navigate(['/search/Hello']);
导航到 localhost/#/search/Hello
然后路由器工作很好,一切都很棒.在该页面上,如果我尝试 this.router.navigate(['/search/World']);
然后浏览器地址栏中的 URL 将相应更新,但组件不会更改全部.
Anyway if I navigate to localhost/#/search/Hello
using this.router.navigate(['/search/Hello']);
then the router works fine and everything is great. While on that page if I try to this.router.navigate(['/search/World']);
then the URL in the browser's address bar will update accordingly but the component doesn't change at all.
以前我可以使用 routerCanReuse
来表示我确实想重用搜索组件,routerOnReuse
会在导航发生时重新运行搜索.我在 @angular/router
中没有看到与这些等效的东西.如何使用新的 URL 参数重新加载当前路由?
Previously I could use routerCanReuse
to indicate that I did want to reuse the search component and routerOnReuse
would rerun the search when the navigation happened. I don't see equivalent's to these in @angular/router
. How can I reload the current route with new URL parameters?
我正在为 @angular/router 的 Angular 2 和 3.0.0-alpha.8 运行 2.0.0-rc.3 版本.
I'm running version 2.0.0-rc.3 for Angular 2 and 3.0.0-alpha.8 of @angular/router.
推荐答案
如果只有参数发生了变化,组件本身将不会再次初始化.但是您可以订阅您发送的参数的更改.
If only the params has changes the component itself won't be initialize again. But you can subscribe to changes in the parameters that you send.
例如在 ngOnInit 方法上,您可以执行以下操作:
For example on ngOnInit method you can do something like this:
ngOnInit() {
this.sub = this.route.params.subscribe(params => {
const term = params['term'];
this.service.get(term).then(result => { console.log(result); });
});
}
这篇关于导航到同一路线不刷新组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!