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



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

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

主页指向http:\localhost:4300frhome联系我们指向http:\localhost:4300frcontact

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

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

http:\localhost:4300eshomehttp:\localhost:4300escontact,但浏览器 URL 仍然http:\localhost:4300fr

如何更新浏览器网址?

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

translate(langCode, language) {
const hostName = document.location.hostname.replace('www.', '');
this.currentTrans = language;
this.currentTransCode = langCode;
this._caseService.GetCaseData(caseUrl,  langCode);
}

this.currentTransCode保存当前语言代码

网址的构造方式如下http:\localhost:4300+this.currentTransCode

您可以使用位置对象

//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);
}

要更改网址,您需要使用正确的语言加载页面。 例如,您可以获取当前路径名,并将语言替换为新语言,并使用新 url 重新加载页面。

document.location.href = "/" + this.currentTransCode + location.pathname.substring(location.pathname.indexOf("/",1)) + location.hash + location.search

更新:

对不起,我想念你使用角度。在这种情况下,您可以使用$location。

$location.path(newUrl);

您可以从这里获取更多详细信息:https://www.consolelog.io/angularjs-change-path-without-reloading/

最新更新