我是 Angular 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);
}
}