Share data between components using TranslateService in Angular 4+

496 views
Skip to first unread message

becto...@gmail.com

unread,
Aug 18, 2017, 5:31:17 AM8/18/17
to Angular and AngularJS discussion
if i am using the translate service in angular4+

Can i share data between components just importing this translateService. Pretty much I want that service to remember which language I set it to. Or is this something i need to create my own service for to share the language i set my app to in order to get it in between components. 
import { TranslateService } from '@ngx-translate/core';


 constructor(public translate: TranslateService, public data: DataService) {
   this.data = data;
   translate.addLangs(['en', 'fr']);
   const browserLang: string = translate.getBrowserLang();
   translate.use(browserLang.match(/en|fr/) ? browserLang : 'en');

}





how could I then in another component figure out which languauge translate.use() was already set to? Or can the translateService not persist data between components and i would have to use the DataService that i wrote myself to store it?

Thanks 

Sander Elias

unread,
Aug 18, 2017, 11:13:15 AM8/18/17
to Angular and AngularJS discussion
Hi,

Just read the documentation, and from it, it looks like it should behave like that as default! You can use the currentLang property of the TranslateService to get the language it's currently in.

Regards
Sander

Stéphane Ancelot

unread,
Sep 20, 2017, 4:36:55 AM9/20/17
to Angular and AngularJS discussion
hi!

Have you succed ? because I have got a problem using the TranslateService.
I made a language-picker component that is a child of the app. 
When it modifies the translate language, it does not change the whole app language.
I don't know if it is a refresh problem . or if the TranslateService is not defined as singleton.

Stéphane Ancelot

unread,
Sep 20, 2017, 4:58:56 AM9/20/17
to Angular and AngularJS discussion
I made further checks in my application.
The language picker changes selection language.
The service is singleton, if I change pages, and request translation using the next code, the translation is well reported.
However, the application does NOT refresh. how to trig a refresh ?? 
I displayed some translations in the language picker, itself, it does not refresh ....altough language is changed.
Is it because it uses translation pipe in the messages that are not refreshed ... ?

 
this.translate.get('my text').subscribe(
  value
=> {
  console
.log("translated :");
  console
.log(value);
 
}




Le vendredi 18 août 2017 11:31:17 UTC+2, becto...@gmail.com a écrit :

Sander Elias

unread,
Sep 20, 2017, 6:02:50 AM9/20/17
to Angular and AngularJS discussion
Hi Stephane,

Just use the JS  to reload the page. I'm pretty sure that 'hot' switching doesn't work right now. It is being considered as a future addition.
https://developer.mozilla.org/en-US/docs/Web/API/Location/reload
Reply all
Reply to author
Forward
0 new messages