Angular 6 router - replace some of the parameters of the current route

坚强是说给别人听的谎言 提交于 2019-12-11 08:07:26

问题


In my Angular 6 solution, the urls have this structure:

/{language}/{app_section}/{object_id}/{view}?queryparams...

A language selector component is shared by all sections of the application, and is included in the template of one of the parent routes so that it appears in all the children routes.

When a user selects a new language, the component should replace only the {language} segment of the current route, leaving everything else unchanged, and navigate to the new route. It seems it should be straightforward to do, but I can't seem to find an easy way. Can anybody help?


回答1:


Yep it is possible. Read the current route, replace the language and navigate to that URL.

constructor(private _router: Router ) {
}

languageSelected(newLanguage) {
  const newUrl = this._router.url.replace(this.currentlanguage, newLanguage);
  this.router.navigateByUrl(newUrl);
}

I've assumed that this.currentLanguage contains the current language exactly as represented in the URL and the newLanguage passed to the method is also in the exact form required by the URL. A technique such as this will trigger a component refresh and temporary state will be lost.



来源:https://stackoverflow.com/questions/52683193/angular-6-router-replace-some-of-the-parameters-of-the-current-route

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