Angular2 router - Navigate to the current page with different parameters

一曲冷凌霜 提交于 2019-12-03 16:20:48

问题


I am trying to route to the current page with different param with no avail. I have a combo box that triggers:

this.router.navigate(['page', selectedId]);

the Url is changing but that's about it.

How do I route to the same page with different param?


回答1:


The page will not refresh, cause that's how the Router works.. without refreshing the page!

You have to subscribe to the route parameters to detect changes in them and then do whatever you want to with that information..

So inject ActivatedRoute into your component and subscribe to the parameters like this:

constructor(private route: ActivatedRoute) {}

ngOnInit() {
  this.route.params.subscribe(params => {
     // PARAMS CHANGED .. TO SOMETHING REALLY COOL HERE ..

     // for example extract the id..
     let id = +params['id']; // (+) converts string 'id' to a number

   });
}



回答2:


you can do this by using this

this.router.navigateByUrl('page_url/' + your_id);

By doing so your params has change successfully.

But it only change your URL if you really want to load some methods then you have to call them menually




回答3:


Ok, after reading all your answers specially @mxii's (thank you for this), I understand that:

  1. when routing to the same page with different param, only the param changes. the DOM stand still, no component rebuild, no onInit cycle.
  2. The OnChanges hook triggers on every data-bind changes, which mean if I pass the param to child component I can't use OnInit on with this param, I must use OnChanges hook.

Good Lesson, Thanks!



来源:https://stackoverflow.com/questions/39613093/angular2-router-navigate-to-the-current-page-with-different-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!