首页 > 解决方案 > 如何在 Angular i18n 路由器模块中使用 LOCALE_ID

问题描述

我正在使用 Angular 的 i18n 设置构建一个小型 Angular 应用程序。一切正常,除了 url 路径和 slug 的翻译。我尝试了一种可能的解决方案,为每种语言提供一个路由模块(如此处所述),但这不起作用。

我以为我可以做类似以下的事情,但我不知道在哪里注入LOCALE_ID

应用程序路由.module.ts

import { LOCALE_ID, NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { MainComponent } from './main/main.component';

const i18nRoutes = {
    de: {
        main: 'inhalte',
        // ...
    }, 
    fr: {
        main: 'contenu',
        // ...
    }
}

const currentLanguage = i18nRoutes[ LOCALE_ID ]; // <-- Apparently not working, since I have to inject LOCALE_ID. But where?

const routes: Routes = [
    {
        path: '',
        redirectTo: currentLanguage.main,
        pathMatch: 'full'
    },
    {
        path: currentLanguage.main + '/:key',
        component: MainComponent
    }
    // ...
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

更新澄清

在中angular.json,我为每种语言的构建过程设置了配置(取自此处,查看 2018 年的修改)

角.json

{
    // ...
    "projects": {
        "my-app": {
            // ...
            "architect": {
                "build": {
                    // ...
                    "configurations": {
                        // ...
                        "de": {
                            "i18nFile": "src/i18n/de.xliff",
                            "outputPath": "dist/de",
                            "i18nFormat": "xlf",
                            "i18nLocale": "de",
                            "baseHref": "/de/"
                            // ...
                        },
                        "fr": {
                            "i18nFile": "src/i18n/fr.xliff",
                            "outputPath": "dist/fr",
                            "i18nFormat": "xlf",
                            "i18nLocale": "fr",                            
                            "baseHref": "/fr/",
                            // ...
                        }
                   }
              }
          }
     }
}

为了一次构建所有应用程序,我输入npm run buildall,它在 中执行以下操作package.json

包.json

{
    "name": "my-app",
    // ...
    "scripts": {
        // ...
        "buildall": "for lang in de fr;do ng build --configuration=$lang; done"
    }
}

它在文件夹的子目录中生成所有应用程序dist就好了。

所以,回到我原来的问题:Exterminator提供的答案不符合我的需要,因为

我希望我解释得够多了。但也许我完全误解了一些东西。无论如何,提前感谢您的帮助。我还在学习,我必须承认一些概念对我来说仍然是模糊的。

标签: angularroutinginternationalization

解决方案


将此添加到 app.module

providers: [{provide: LOCALE_ID, useValue: 'fr-FR'}]

然后在您想要的任何地方使用以下方法调用它

import {LOCALE_ID} from '@angular/core';

  constructor(@Inject(LOCALE_ID) locale: string){
    console.log('locale', locale);
  }

你也可以使用这个方法

platformBrowserDynamic([{provide: LOCALE_ID, useValue: 'en-EN'}]).bootstrapModule(AppModule, {providers: [{provide: LOCALE_ID, useValue: 'en-EN'}]});

推荐阅读