I'm trying to get available languages, but the service returns undefined. I don't see a setLangs() method, so just wondering how they should be set.
constructor(public translate: TranslateService) {
// use navigator lang if available
var userLang = navigator.language.split("-")[0];
userLang = /(es|en)/gi.test(userLang) ? userLang : "en";
// this language will be used as a fallback when a translation isn't found in the current language
translate.setDefaultLang("en");
// the lang to use, if the lang isn't available, it will use the current loader to get them
translate.use(userLang);
var avLang = translate.getLangs();
console.log("available languages: ", avLang);
}
getLangs method return currently loaded languages. I think that 'en' language isn't correctly loaded. Look up to browser network for xhr request with language json.
Few days ago i made pull request with setter and getter with available languages list - https://github.com/ocombe/ng2-translate/pull/173
I've investigated a bit further and I've found what it was. Basically, the ng2-translate service is not available until quite late in the component's lifecycle. I've tried logging with all the hooks and to my surprise the translate service was not available until ngAfterContentChecked. At that moment I get a lot of logging (I guess because Angular 2 does double checking in dev mode).
To make matters even more complicated, I can't replicate exactly when the service is available. ngAfterContentChecked doesn't always work. ngAfterViewChecked seems more reliable but that will be running code many times.
I'm using the translate service as a singleton, and I suppose that's the reason why it's not available earlier on. Is there not a better way of having the translation service as a global singleton and available at init?
GOT IT! The solution is an observer pattern. I'm now subscribing to onLangChange and that gives me the time to have my flow within onNgInit.
I was wondering if info about available languages, default, etc. could be made an observable too
Well anything could be an observable, but you'd have to convince me for the necessity of this :)
@cortopy you can observe the defaultLangChange event now as well in 5.0.0.
For what it's worth, I had the same problem until I added "private"...
constructor(private translate: TranslateService) {
...
}
Most helpful comment
For what it's worth, I had the same problem until I added "private"...