首页 文章

导航到相同的路线而不刷新组件?

提问于
浏览
39

我已升级为使用路由器弃用的新Angular 2路由器,并且某些行为已更改 .

页面我'm having issues with is a search page. We'已选择使用 HashLocationStrategy 将所有搜索词放入URL中 . 路线看起来像这样:

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 }
];

我知道查询字符串方法可能更适合所有这些选项,但项目要求由其他人决定......

无论如何,如果我使用 this.router.navigate(['/search/Hello']); 导航到 localhost/#/search/Hello ,那么路由器工作正常,一切都很好 . 在该页面上,如果我尝试 this.router.navigate(['/search/World']); ,则浏览器's address bar will update accordingly but the component doesn'中的URL会发生变化 .

以前我可以使用 routerCanReuse 表示我确实要重用搜索组件, routerOnReuse 会在导航发生时重新运行搜索 . 我在 @angular/router 中没有't see equivalent' . 如何使用新的URL参数重新加载当前路由?

我正在运行Angular 2的2.0.0-rc.3版和@ angular / router的3.0.0-alpha.8版 .

1 回答

  • 43

    如果只有params有变化,组件本身将不会再次初始化 . 但您可以订阅您发送的参数的更改 .

    例如,在ngOnInit方法中,您可以执行以下操作:

    ngOnInit() {
        this.sub = this.route.params.subscribe(params => {
           const term = params['term'];
           this.service.get(term).then(result => { console.log(result); });
         });
      }
    

相关问题