繁体   English   中英

从组件或服务访问 Angular2 翻译

[英]Access Angular2 translation from component or service

我目前正在根据https://angular.io/docs/ts/latest/cookbook/i18n.html 中的指南翻译我的第一个 Angular2 应用程序

这些示例始终仅显示如何将i18n属性应用于模板代码以及模板代码随后如何国际化。

我将如何从组件的代码( .ts文件)或服务内部访问本地化文本? 我需要它来与我正在使用的一些 JavaScript 库进行交互,在那里我需要使用本地化文本调用 JavaScript 函数。

如果您使用的是ng2-translate模块,则只需注入TranslateService

constructor(private translateService: TranslateService) { }

并使用它的get(translationKey: string)方法返回一个Observable

this.translateService.get('stringToTranslate').subscribe(
    translation => {
        console.log(translation);
    });

我正在使用属性翻译功能

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

@Component({
    selector: 'app-sandbox',
    templateUrl: 'sandbox.html'
})
export class SandboxComponent implements OnInit {
    @Input()
    public title: string;

    constructor() {
    }

    ngOnInit() {
        console.log('Translated title ', this.title);
    }
}

从父组件模板:

<app-sandbox i18n-title title="Sandbox"></app-sandbox>

这是一种解决方法,但我仍然认为它是迄今为止最干净的方法。 它使您可以访问ts的翻译title

  constructor(private translate: TranslateService) { }

  this.translate.get(this.pageTitle).subscribe((text:string) => {
      this.translate.onLangChange.subscribe((event: LangChangeEvent) => {
        title.setTitle(this.translate.instant(text))
      });
    });        

如果您想检测使用下面代码的语言更改,请传递您的标题键

this.setDocTitle('dashboard.title');

setDocTitle(titleKey: string) {
  this.translate.onLangChange.subscribe((event: LangChangeEvent) => {
    this.translate.get(titleKey).subscribe((text:string) => {
    this.titleService.setTitle(this.translate.instant(text));
  });
  }); 
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM