Angular 9 returns 文本本身中的全局 $localize 方法

Global $localize method in Angular 9 returns the text itself

我一直在关注如何使用 $localize 的教程,并尝试按如下方式使用它:

我的angular.json(相关部分):

        "build": {
          ...
          "configurations": {
            ...
            "fr-FR": {
              "aot": true,
              "outputPath": "dist/fr-FR",
              "i18nFile": "src/locale/messages.fr.xlf",
              "i18nFormat": "xlf",
              "i18nLocale": "fr-FR",
              "i18nMissingTranslation": "error"
            }
          }
        },
        "serve": {
         ...
          "configurations": {
            ...
            "fr-FR": {
              "browserTarget": "frontend:build:fr-FR"
            }
          }
        },

和 运行 应用:ng serve --configuration=fr-FR

当我在模板中使用 i18n 属性时,如下所示:

<p i18n="@@profile">Profile</p>

并且在我的 messages.fr.xlf 中有以下条目:

      <trans-unit id="profile" datatype="html">
        <source>Profile</source>
        <target>Profil</target>
        <context-group purpose="location">
          <context context-type="sourcefile">src/app/profile/profile.component.html</context>
          <context context-type="linenumber">34</context>
        </context-group>
      </trans-unit>

一切正常。但现在我需要访问打字稿中的翻译,比如 (profile.component.ts)。为此,我有以下内容:

let profileText = $localize`:@@profile`;
console.log(profileText);

这会导致控制台出现以下错误:

ERROR Error: Unterminated $localize metadata block in ":@@profile".

如果我尝试如下:

let profileText = $localize`:@@profile:Profile`;
console.log(profileText);

错误消失了,但它总是打印 Profile,而不是翻译。我错过了什么?

更新:

请找到StackBlitzlink。事情是这样的;我认为当 运行ning 和行为相同时,StackBlitz 不会考虑 --configuration=fr-FR(来自 package.json)。

更新二:

StackBlitz link 可能会产生误导,因为我不知道如何 运行 具有特定配置的项目(比如 --configuration=fr-FR)。所以我在 Github 回购中复制了这个问题。

从您的 tsconfig.json 中删除 enableIvy: false(基本上启用 Ivy)并根据 doc 更正您的 angular.json 中的 i18n 配置:

{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "newProjectRoot": "projects",
  "projects": {
    "project-name": {
      ...
      "i18n": {
        "sourceLocale": "en-US",
        "locales": {
          "fr": "src/locale/messages.fr.xlf"
        }
      },
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          ...
          "configurations": {
            "fr-FR": {
              "localize": [
                "fr"
              ]
            },
            ...
          }
        },
        "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          ...
          "configurations": {
            "fr-FR": {
              "browserTarget": "project-name:build:fr-FR"
            },
            ...
          }
        },
        ...
      }
    }
  },
  ...
}