问题
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