【问题标题】:Get the value of --locale on runtime for an AOT compiled Angular App在运行时为 AOT 编译的 Angular 应用程序获取 --locale 的值
【发布时间】:2018-11-24 11:31:18
【问题描述】:

我有一个多语言应用程序,它在每种语言中都使用 --aot 编译,例如德语:

ng build --aot --env=prod --prod --build-optimizer --i18nFile=src/locale/DARI_messages_de_DE.xlf --i18nFormat=xlf --locale=de --missingTranslation warning --output-path dist/de --base-href /de/

我们需要在运行时获取 locale 的值,以便将其也处理到我们的后端。

如果已经尝试过从

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

constructor(private modalService: BsModalService) {
  console.log("LOCALE_ID", LOCALE_ID);
}

但是 LOCAL_ID 是空的,我认为它仅用于 JIT

有什么方法可以在运行时获取这个参数吗?

【问题讨论】:

  • 您使用的是哪个 Angular 版本?我在 Angular 6 上,使用 --i18n-locale=de 仍然会产生 'en-US' 的 LOCALE_ID。
  • @Simon 这是 Angular 的默认位置

标签: angular internationalization angular2-aot angular-i18n


【解决方案1】:

作为一个新手,我发现 Simons 的回答有点不完整。原来你需要同时导入 LOCALE_ID 和 Inject:

import { Component, OnInit, LOCALE_ID, Inject } from '@angular/core';

@Component({
  selector: '...',
  templateUrl: '...',
  styleUrls: ['...']
})

export class ShinyComponent implements OnInit {

  constructor(@Inject(LOCALE_ID) protected localeId: string) { }

  public someFunction {} {
    console.log("Current locale is "+this.localeId); 
  }
}

ngOnInit() {}

【讨论】:

  • 还有其他方法吗?我想在不使用构造函数的情况下做到这一点。有可能吗?
  • 我在 Angular 10 中仍然这样做。我还没有发现任何其他方法。
【解决方案2】:

你应该让 Angular 注入 LOCALE_ID

constructor(private modalService: BsModalService,
    @Inject( LOCALE_ID ) protected localeId: string) {
    console.log("LOCALE_ID", localeId);
}

【讨论】:

    猜你喜欢
    • 2017-11-30
    • 2017-03-17
    • 1970-01-01
    • 2021-12-25
    • 2011-06-07
    • 2021-03-10
    • 2017-03-10
    • 1970-01-01
    • 2021-12-31
    相关资源
    最近更新 更多