[英]Angular 2 routes - redirect to different app
我正在以其他語言生成應用程序的各種版本。 我正在使用AOT(提前)編譯,因此最終得到的靜態可部署網站的結構如下所示:
dist -
index.html -- entry file for the default (English language) app
-fr
index.html -- entry file for French language version
-de
index.html -- entry file for German language version
目前,我可以使用下拉菜單在主要語言網站之間進行切換,用戶可以在其中選擇首選語言,然后使用純JavaScript加載所需站點的主要條目文件,如下所示:
const baseUrl = window.location.origin;
window.location.href = baseUrl + '/' + requestedLanguage + '/index.html'; // e.g. requestedLanguage = 'fr'
這可行,因為似乎請求實際的index.html
文件意味着Angular不會將請求href
解釋為Angular路由。
不過,我想發生的是,當用戶在路徑中輸入已經包含語言版本的URL時,我希望該語言版本得到處理。 我還希望保留URL路徑,以便Angular路由為請求的URL加載適當的組件。
例如:
用戶輸入myDomain.com/fr/myPage
會加載/fr/
子目錄下的應用程序,並且該應用程序中的Angular路由會加載MyPage
的相關組件
當前,如果我輸入URL myDomain.com/fr/myPage
,那么Angular路由會嘗試將所需的子文件夾fr
解釋為一條不存在的路由,因此出現以下錯誤:
Error: Cannot match any routes. URL Segment: 'fr/instruments'
如何加載所需的應用程序和正確的組件? 必須有一種方法使Angular認識到URL中的fr
引用了另一個應用程序。 也許我缺少構建配置之類的東西? 這是我在package.json
用於構建法語版本的腳本:
"build:fr": "ng build --aot --output-path=dist/fr --base-href /fr/ --i18nFile=src/locale/messages.fr.xlf --i18nFormat=xlf --locale=fr",
只需使用組件而不是其他單獨的應用程序,然后使用以下示例>
{path:'',component:EnHomeComponent},
{path:'contact',component:EnContactComponent},
{path:'fr',component:LayoutComponent,
children:[
{path:'',component:FrHomeComponent},
{path:'contact',component:FrContactComponent}]}
那么您可以通過URL直接訪問頁面
對英語,法國和丹麥語的不同路徑使用角形router
概念。
然后使用基於語言的路徑。
通過像這樣為.NET后端配置管道,我能夠加載應用程序的不同語言版本,以便為每種不同語言的應用程序(在代碼中稱為“ SPA”)加載Angular靜態索引頁面。 它通過檢查請求URL中的第一個子文件夾是否有一個“ index.html”頁面(例如“ / fr /”,“ / de /”)來工作,並加載該頁面(如果存在):
public class Startup
{
public void Configuration()
{
app.Use((context, next) =>
{
if (!context.Request.Path.HasValue)
return next();
IFileInfo fi;
string spaIndex = "index.html";
Uri uri = new Uri(context.Request.Uri.ToString());
var segs = uri.Segments;
var folder = segs.Length > 1 ? String.Format("/{0}", segs[1]) : "/";
if (!physicalFileSystem.TryGetFileInfo(context.Request.Path.Value, out fi)) {
// check if this is a request for a sub-application, e.g an alternative language version
// if so, load the app
if (physicalFileSystem.TryGetFileInfo(String.Format("{0}{1}", folder, spaIndex), out fi))
{
context.Request.Path = new PathString(String.Format("{0}{1}", folder, spaIndex));
}
}
return next();
});
}
}
URL的其余部分(語言子文件夾之后的部分)隨后被解釋為已加載的應用程序(例如法語應用程序)內部的路由。 這意味着已為該應用程序加載了正確的組件(我不完全確定這部分是如何工作的-也許路徑的其余部分會落入.NET請求管道的其他部分,然后傳遞到Angular應用程序中? )
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.