如何在Angular项目的源代码中使用i18t的文本?

时间:2017-05-18 12:22:51

标签: angular internationalization

我正在使用Angular 4的i18n功能,并使用目标语言中的angular-cli成功构建项目。 HTML模板已正确翻译。但是我在javascript代码中得到了一些文本。

推荐的本地化js源中使用的字符串的方法是什么    验证之类的东西? 我们可以期待i18n能够提供解决方案吗?

目前我正在使用区域设置来确定要使用的转换。 区域设置来自ng serve --locale frng build --locale fr

建立/服务如下:

ng serve --aot --locale fr  ...

并使用代码中的语言环境,如下所示:

import { LOCALE_ID } from '@angular/core';
// ...
constructor (@Inject(LOCALE_ID) locale: string) {
}

(我正在关注http://blog.danieleghidoli.it/2017/01/15/i18n-angular-cli-aot/

的重要提示

3 个答案:

答案 0 :(得分:2)

使用代码中的I18nPipe

constructor(private translator: I18nPipe) {
    let translatedText = this.translator.transform('Hello');
}

其中transform()I18nPipe类中提供string参数的方法的翻译方法。例如:

i18n管道:

@Pipe({
    name: 'i18n',
    pure: false
})
export class I18nPipe implements PipeTransform {

    constructor(public i18nService: I18nService) {
    }

    transform(phrase: any, args?: any): any {
        return this.i18nService.getTranslation(phrase);
    }

}

<强> i18nService:

@Injectable()
export class I18nService {

    public state;
    public data: {};

   getTranslation(phrase: string): string {
        return this.data && this.data[phrase] ? this.data[phrase] : phrase;
    }

    private fetch(locale: any) {
        this.jsonApiService.fetch(`/langs/${locale}.json`)
            .subscribe((data: any) => {
                this.data = data;
                this.state.next(data);
                this.ref.tick();
            });
    }
}

i18nService中,您使用fetch()方法获取当前语言,并通过自定义API服务(在我的情况下为jsonApiService),您可以从es.json获取数据,en.json,de.json等(取决于您的local参数),在getTranslation()中,您实际上正在翻译给定参数并将其返回给它翻译价值。

更新1:

有了这个,您可以拥有es.json

这样的文件
"hello": "Hola",
"sentence1": "This is the sentence 1",
"goodbye": "Adiós"

@Pipe可以在代码中使用,以便在.component.ts文件中应用翻译,就像我上面显示的那样(这对于使用Ajax呈现的DataTable很有用)< / em>的。

或者可以在您的模板中应用,只需:

{{ 'hello' | i18n }}
{{ this.goodbyeStringVariable | i18n }}

答案 1 :(得分:1)

我们现在(2019年初)正在使用Angular 7,看来仍然不支持在TypeScript源文件中本地化静态字符串。

因此,我们提出了一种简单的方法(如果是“ hacky”):

  1. 向模板添加隐藏的HTML元素,其内容设置为JavaScript代码中的静态字符串:
<!-- string table -->
<span #toolTipText hidden i18n="Tool tip text|Text displayed on the tooltip@@TOOLTIP_TEXT">Do not click this or bad things will happen.</span>
<span #errorOccured hidden i18n="Error notification|Error message displayed when the user ignores the warning on the tooltip@@ERROR_MESSAGE">A very bad thing just happened.</span>
  1. 使用@ViewChild()装饰器在代码中引用此隐藏元素:
@Component({
  // ...
})
export class BadThingsComponent implements OnInit {

  // "string table" elements for i18n
  @ViewChild('toolTipText') warningMsg;
  @ViewChild('errorOccurred') errorMsg;

  // ...
  1. 通过寻址修饰的类成员的.nativeElement.innerText,获取以前在代码中为静态字符串的字符串值:
onTryToPreventBadThings(event: CustomEvent) {
    // ...

    this.preventer.messageToDisplay = this.warningMsg.nativeElement.innerText;

    // ...
  }

  onBadThingDidHappen(event: CustomEvent) {
    // ...

    this.notifier.message = this.errorMsg.nativeElement.innerText;

    // ...
  }

答案 2 :(得分:0)

似乎Angular还没有支持这个。我使用默认的Angular i18n方法的混合物,因为工具链非常好并且是第三方工具,如angular-l10n。后来的好处是它自动执行用于获取具有翻译的资源文件的常见内容,即从fr-FR回退 - > fr - &gt;如果没有可用的翻译并提供其他方便的功能,如翻译中的占位符。手动方法不提供此功能。

我在我的服务中使用此功能,如下所示:

constructor(translationService: TranslationService) {}
...
foo() {
    this.translationService.translate('httpService.pagingError')
}

在app starter app.module.ts中,我稍微修改了设置以从应用加载默认语言环境。注意构造函数。

import { L10nConfig, L10nLoader, TranslationModule, StorageStrategy, ProviderType } from 'angular-l10n';

const l10nConfig: L10nConfig = {
    locale: {
        languages: [
            { code: 'en', dir: 'ltr' },
            { code: 'de', dir: 'ltr' }
        ],
        language: 'en',
        storage: StorageStrategy.Cookie
    },
    translation: {
        providers: [
            { type: ProviderType.Static, prefix: './assets/locale-' }
        ],
        caching: true,
        missingValue: 'No key'
    }
};

@NgModule({
    imports: [
        BrowserModule,
        HttpClientModule,
        TranslationModule.forRoot(l10nConfig)
    ],
    declarations: [AppComponent, HomeComponent],
    bootstrap: [AppComponent]
})
export class AppModule {

    constructor(public l10nLoader: L10nLoader, public localeService: LocaleService,
              @Inject(LOCALE_ID) locale: string) {
        this.l10nLoader.load().then(() => this.localeService.setDefaultLocale(locale));
    }

}