I18n 使用 firebase 托管和 Angular 在 baseHref 中获取正确的语言代码

问题描述 投票:0回答:1

在我的 Angular 项目中,我为“sv”(瑞典语)和“en”设置了 i18n。

我想要的是在访问 mypage.com 时,将“/sv”或“/en”添加到 baseHref 这样正确的index.html就会从基于“接受语言”的Firebase托管加载,换句话说,瑞典用户将获得“mypage.com/sv”,而其他所有人将加载mypage.com/en。

我做了一些挖掘,似乎这并不是 Firebase 托管自动带来的,必须在 Angular 或 Firebase 函数中添加一些逻辑。

在角度中添加逻辑完全失败(请记住,我希望它自动发生,而不是用户在下拉列表中选择的东西)

...以及 firebase 函数的逻辑,尽管它在最简单的级别上工作,但它扰乱了我的路由(在不应该添加大量“/sv”到路径时+感觉像是一个修复)。此修复的以下代码:

exports.redirectBasedOnLanguage = functions.https.onRequest((req:any, res:any) => {
// Default to English
let language = 'en';

// Check for the Accept-Language header and prefer Swedish if present
const acceptLanguage = req.headers['accept-language'];
if (acceptLanguage && acceptLanguage.startsWith('sv')) {
    language = 'sv';
}

// Construct the redirect URL based on the detected language
// Note: You might want to adjust the path construction based on your URL structure
const targetUrl = `/${language}${req.path}`;

// Perform the redirection
res.redirect(302, targetUrl);

});

我的 firebase.json: 对于上述解决方案:

    "rewrites": [
  {
    "source": "**",
    "function": "redirectBasedOnLanguage"
  }
];

并且在没有任何 firebaseFunctions 修复的情况下进行设置(当遵循文档时):

    "rewrites": [
  {
    "source": "/sv{,/**}",
    "destination": "/sv/index.html"
  },
  {
    "source": "/sv-SE{,/**}",
    "destination": "/sv/index.html"
  },
  {
    "source": "**",
    "destination": "/en/index.html"
  }
]

正确的处理方法是什么?

angular firebase internationalization angularfire2 firebase-hosting
1个回答
0
投票

您可能想看看这个 Firebase 托管 i18n 配置。

https://firebase.google.com/docs/hosting/i18n-rewrites

© www.soinside.com 2019 - 2024. All rights reserved.