当组件的属性更改时如何更新浏览器 URL?

xai*_*oft 2 angular

如果我浏览到http:\\localhost:4300\fr,我的主页就会加载法语翻译。

我的导航中有 2 个链接(主页、联系我们)。

首页 指向http:\\localhost:4300\fr\home 联系我们 指向http:\\localhost:4300\fr\contact

我还有一个下拉菜单,用户可以在其中选择一种语言,它将返回翻译后的页面。

例如,当我选择西班牙语时,链接会更新为:

http:\\localhost:4300\es\homehttp:\\localhost:4300\es\contact,但浏览器 URL 仍保留http:\\localhost:4300\fr

如何更新浏览器网址?

这是当用户从下拉列表中选择语言时我使用的代码:

  translate(langCode, language) {
    const hostName = document.location.hostname.replace('www.', '');

    this.currentTrans = language;
    this.currentTransCode = langCode;
    this._caseService.GetCaseData(caseUrl,  langCode);
  }
Run Code Online (Sandbox Code Playgroud)

this.currentTransCode保存当前语言代码

url 的构造如下http:\\localhost:4300\+this.currentTransCode

Dav*_*vid 5

您可以使用位置对象

//component or service.ts
import {Location} from '@angular/common'

constructor(private location: Location)
{
}

changeCurrentUrl()
{
    let parts = window.location.pathname.split('/');
    parts[1] = this.currentTransCode; //replaces 'fr' with 'en'
    this.changeUrl(parts.join('/'));
}
 changeUrl(url: string)
 {
    this.location.replaceState(url);
 }
Run Code Online (Sandbox Code Playgroud)