I am new to angular 2 and i am building my first app. I have problems understanding how to change the language globally, from a single place. Right now i can change language in a Component. I am using a cookie to store selected language and is available globally via a service. From what i understand i think i have to use a listener for this but don't know how to put it in practice or if this is the correct way. An example will be much appreciated.
Thanks
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);
}
}
and the service
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);
}
}