I have an app with lazy loaded modules. I also have a shared module called MainModule. Here is my very simple service called LangService:
@Injectable({
providedIn: 'root'
})
export class LangService {
lang:string = "en";
constructor(public translate: TranslateService) {
this.translate.setDefaultLang( this.lang );
this.translate.use( this.lang );
}
setLang( lang ) {
this.translate.setDefaultLang( this.lang );
this.translate.use( this.lang );
this.lang = lang;
}
}
In my tabs routing I have the following:
changeLang(lang) {
// lang is for example "fr"
this.langService.setLang(lang);
}
And my tabs html:
<Label [text]="'HOME.Title' | translate"></Label>
Now when I go to another route, in it's component I get the default value (not the changed value):
constructor(public langService:LangService) {
// prints "en" !!!
console.log(this.langService.lang);
};
I have provided the service in my shared module and import my shared module in everywhere:
providers: [
LangService
],
I'm using Angular 7 with nativescript.
@Injectable({ providedIn: 'root' })and not as provider of SharedModule. This will allow you to have only on instance of it and will be available across the app,providersfrom any other module orMainModuleprovidersit doesn't work. See updates please.