【问题标题】:Angular routing, internationalization, and deploymentAngular 路由、国际化和部署
【发布时间】:2021-10-20 13:13:44
【问题描述】:

我们有一个 Angular 12 应用程序,它具有多个模块,例如 ShippingModule、ReceivingModule 等。我们已经适当地设置了路由,并且可以使用简单的路径访问每个模块,例如 localhost:4200/Shipping 和 localhost:4200/Receiving。

我们已将其国际化,并希望将其部署到 nginx 服务器。当我们构建时,dist 目录包含三个完整的应用程序,一个用于 'en'、'es' 和 'vt',非常完美。

https://angular.io/guide/i18n-common-deploy 的文档说我们将主应用程序托管在一个 url 下,并根据用户的接受语言重写。所以如果我去www.internaladdresss.com/Shipping,它会把我改写成www.internaladdress.com/en/Shipping

但是,我们是否需要重新编码 routes 模块以具有语言 id 变量,或者是否在每个 index.html 文件中都有 basehref 可以防止这种需要?我们的示例路由模块的路由定义如下:

const routes: Routes[
{ path: 'shipping', loadChildren: () => import('./shippingdashboard/shipping.module').then(m=>m.ShippingDashboardModule)},
{ path: 'receiving', loadChildren: () => import('./receivingdashboard/receiving.module').then(m => m.ReceivingDashboardModule)}];
@NgModule({
import: [RouterModule.forRoot(routes)],
exports:[RouterModule]
})
export class AppRoutingModule{}

为了使 URL 起作用,我们是否需要定义像 path: 'langId:/shippinglangId:/receiving 这样的路由?

【问题讨论】:

    标签: angular nginx routes internationalization


    【解决方案1】:

    要回答任何人的疑问,答案是“不,您不需要为 URL 路径中的语言标识符编码。”

    生成的每个 index.html 文件都在标头中设置了基本 href:

    对于英语,

    <base href="/en/">
    

    西班牙语

    <base href="/es/">
    

    等等

    真正的工作来自 nginx 配置。

    显然,映射传入请求的第一件事是接受语言

    map $http_accept_language $accept_language {
        ~*^es es;
        ~*^en en;
    }
    

    接下来的部分经过了一些尝试和错误,但一旦你看到它就非常简单:

    # Fallback to default language if no preference defined by browser
    if ($accept_language ~ "^$") {
      set $accept_language "en";
    }
    
    # Redirect "/" to Angular application in the preferred language of the browser
    rewrite ^/$ /$accept_language permanent;
    
    # Everything under the Angular application is always redirected to Angular in the
    # correct language
    location ~ ^(?!/(en|es)) {
      try_files $uri /en/index.html$args =404;
    }
    

    最后一个领域是解决方案的真正症结所在。如果用户指定的语言不是任何受支持的语言,则默认将他们的请求重定向到英语站点下方。

    总而言之,您无需将语言标识符编程到路由器中。大部分工作只是设置 nginx 以根据检测到的语言(或缺少语言)正确解释和重定向到正确的站点文件夹。

    【讨论】:

      猜你喜欢
      • 2011-09-07
      • 1970-01-01
      • 2017-06-09
      • 1970-01-01
      • 1970-01-01
      • 2018-04-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多