angular2多语言实现

angular2多语言实现,angular,Angular,我有多语言服务 import {Injectable, Inject} from '@angular/core'; import { TRANSLATIONS } from './translations'; // import our opaque token @Injectable() export class TranslateService { private _currentLang: string; public get currentLang() { r

我有多语言服务

    import {Injectable, Inject} from '@angular/core';
import { TRANSLATIONS } from './translations'; // import our opaque token

@Injectable()
export class TranslateService {
  private _currentLang: string;

  public get currentLang() {
    return this._currentLang;
  }

  // inject our translations
  constructor(@Inject(TRANSLATIONS) private _translations: any) {
  }

  public use(lang: string): void {
    // set current language
    this._currentLang = lang;
  }

  private translate(key: string): string {
    // private perform translation
    let translation = key;

    if (this._translations[this.currentLang] && this._translations[this.currentLang][key]) {
      return this._translations[this.currentLang][key];
    }

    return translation;
  }

  public instant(key: string) {
    // public perform translation
    return this.translate(key);
  }
}
所以,这适用于我选择的组件。但在转到另一个组件并返回后,语言设置为默认值


可能还记得localStorage中选择的语言吗?有人知道如何记住所选的语言吗?

在一个小项目中,你的设置看起来像我的,所以我在这里冒险。如果这是正确的,请在问题中添加来自您的组件的基本代码,以便其他用户能够理解:)

但在翻译服务中,您设置了当前语言,可以从您提供的代码中看到:

  public get currentLang() {
    return this._currentLang;
  }
然后将此服务注入组件中,我将其命名为
\u translateService
,因此仅在您的OnInit方法中检查当前选择的语言。它应该是这样的:

this.selectLang(this._translateService._currentLang);
selectLang方法,当用户选择语言选项时也会激发该方法

selectLang(lang: string) {
    this._translateService._currentLang = lang; // if user makes choice on some component, the new chosen language is pushed to service
    this._translateService.use(lang); // the method in your service
    this.refreshText(); // method that updates the content to current language
}
希望这有帮助,如前所述,添加
selectLang
-方法(或类似名称),以防您在应用程序中使用类似的方法。作为参考,这是我用过的例子,我想你也用过:


您在哪里声明此服务的提供商?我在应用程序中声明它。moduleVahe,此回答对您有帮助吗?:)