应用程序中的Angular 2翻译更改语言

时间:2017-01-03 23:07:40

标签: angular typescript translation

我是角度2的新手,我正在构建我的第一个应用程序。我在理解如何从一个地方全局改变语言方面遇到了问题。现在我可以更改组件中的语言。我使用cookie来存储所选语言,并通过服务在全球范围内提供。根据我的理解,我认为我必须使用听众,但不知道如何将其付诸实践或如果这是正确的方法。一个例子将非常感激。

由于

import {Component} from "@angular/core";
import {TranslateService} from "ng2-translate";
import {SettingsService} from "../settings.service";

@Component({
    selector: 'rn-header',
    templateUrl: './header.html',
    styleUrls: ['./header.scss']
})
export class HeaderComponent {

    constructor(private translate: TranslateService, private settings: SettingsService) {
        translate.setDefaultLang(settings.getLanguage());
        translate.use(settings.getLanguage());
    }

    changeLanguage(language) {
        console.log('Language changed to: '+language);
        this.settings.setLanguage(language);
        this.translate.use(language);

    }

}

和服务

import {Injectable} from "@angular/core";
import {CookieService} from "angular2-cookie/services/cookies.service";

@Injectable()
export class SettingsService {
    defaultLanguage: string = 'en';

    constructor(private _cookieService: CookieService) {

    }

    getLanguage() {
        if (this._cookieService.get('RN_LANGUAGE_PREFERENCE')) {
            return this._cookieService.get('RN_LANGUAGE_PREFERENCE');
        }

        return this.defaultLanguage;
    }

    setLanguage(language: string) {

        this._cookieService.put("RN_LANGUAGE_PREFERENCE", language);
    }

}

1 个答案:

答案 0 :(得分:0)

// Best way to change language Globally is to use pipes and send the language parameter as an argument.
// This would automatically change the Language across the components where the language pipe is utilized.
// The following example can be used to supple multiple language at a time and can be used to change Language dynamically on a single click

// for example: **language.pipe.ts**

`import { Pipe, PipeTransform, OnInit, OnChanges } from '@angular/core';
import { LanguageService } from '../services/language.service';

@Pipe({
    name: 'language'
})
export class LanguagePipe implements PipeTransform {

    constructor(
        public lang: LanguageService
    ) { }

    transform(value: string, args?: any): any {
        return this.lang.getLang(value);
    }
}
`

// **language.service.ts**

`import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';

@Injectable()
export class LanguageService {

    selectedLanguage = 'ch';
    segmentsNames: any = {};
    constantSegmentNames: any = {};
    language = {
        undefined: { 'en': '', 'ch': '' },
        null: { 'en': '', 'ch': '' },
        '': { 'en': '', 'ch': '' },
        'hello': { 'en': 'Hello', 'ch': '你好' },
        'world': { 'en': 'World', 'ch': '世界' }
    };

    constructor(private _http: HttpClient) { }

    getLang(value: string, args?: any): any {
        if (this.language[value]) {
            return this.language[value][this.selectedLanguage];
        }
        return value;
    }

    /**
     * @function that is used to toggle the selected language among 'en' and 'ch'
     */
    changeLanguage() {
        if (this.selectedLanguage === 'en') {
            this.selectedLanguage = 'ch';
        } else {
            this.selectedLanguage = 'en';
        }
    }
}
`

// **Use Language Pipe in HTML AS**

`<strong>{{'hello' | language:lang.selectedLanguage}}{{'world' | language:lang.selectedLanguage}}</strong>`

PS:不要忘记在要使用此功能的所有组件中导入管道和服务