Reputation: 5263
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.
Upvotes: 0
Views: 381
Reputation: 8478
In stead of providing the module in the MainModule
which seems to create another instance each time a new module is loaded. You should be making your services Injectable
at root.
Ex:
@Injectable({
providedIn: 'root'
})
export class LangService {
}
The service now will have only one instance and can be used across and any updates will be visible to all modules. Also make sure to remove it from list of providers
from any other module.
Any service injections to this service, should also be injected in root
and not be part of providers of MainModule
.
Check this example that i created here: The language set in app.component will display in the customer details screen which is lazy-loaded
Unless you are resetting the language anywhere else, it will show up as is.
Upvotes: 1