我们在prod上有一个两种语言的应用程序fr和en,您必须为每种语言和不同的基本url构建您的应用程序,在我的示例中,我已经在包中添加了.json
"scripts": {
...
"build-i18n:fr": "ng build --output-path=dist/fr --aot -prod --bh /fr/ --i18n-file=src/locale/messages.fr.xlf --i18n-format=xlf --locale=fr",
"build-i18n:en": "ng build --output-path=dist/en --aot -prod --bh /en/ --i18n-file=src/locale/messages.en.xlf --i18n-format=xlf --locale=en",
"build-i18n:default": "ng build --output-path=dist/en --aot -prod --bh /en/",
"build-i18n": "npm run build-i18n:default && npm run build-i18n:fr"
},
之后,您必须添加web服务器配置以提供这两个应用程序,每个应用程序都位于子目录中:
https://www.yourapp.com/en/
https://www.yourapp.com/fr/
下面是IIS的一个示例
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<directoryBrowse enabled="true" />
<rewrite>
<rules>
<rule name="Imported Rule 1" stopProcessing="true">
<match url="^../index\.html$" ignoreCase="false" />
<action type="None" />
</rule>
<rule name="Imported Rule 2" stopProcessing="true">
<match url="(..)" ignoreCase="false" />
<conditions logicalGrouping="MatchAll">
<add input="{REQUEST_FILENAME}" matchType="IsFile" ignoreCase="false" negate="true" />
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" ignoreCase="false" negate="true" />
</conditions>
<action type="Rewrite" url="{R:1}/index.html" />
</rule>
<rule name="Imported Rule 3">
<match url="^$" ignoreCase="false" />
<conditions logicalGrouping="MatchAll">
<add input="{HTTP_ACCEPT_LANGUAGE}" pattern="^fr" />
</conditions>
<action type="Redirect" url="/fr/" redirectType="Found" />
</rule>
<rule name="Imported Rule 5">
<match url="^$" ignoreCase="false" />
<conditions logicalGrouping="MatchAll">
<add input="{HTTP_ACCEPT_LANGUAGE}" pattern="^es" negate="true" />
</conditions>
<action type="Redirect" url="/en/" redirectType="Found" />
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>
您必须添加一些代码来管理语言切换组件中两个应用程序之间的导航。获取当前url,然后重定向
<ul class="dropdown-menu" *ngIf="!isDev">
<li *ngFor="let language of languages;let i=index" >
<a id="TopNavLinkLanguageName{{ i}}" href="/{{language.lang}}/#{{getCurrentRoute()}}" (click)="changeLanguage(language.lang)">
<img [src]="..." alt="flg" />
</a>
</li>
</ul>
你的ts文件
getCurrentRoute() {
return this.router.url;
}
changeLanguage(lang: string) {
const langs = ['en', 'fr'];
this.languages = this.allLanguages.filter((language) => {
return language.lang !== lang;
});
this.curentLanguage = this.allLanguages[langs.indexOf(lang)].name
localStorage.setItem('Language', lang);
if (isDevMode()) {
location.reload(true);
}
}