I'm little confused about singleton services on Angular 2. I need a translate service in whole application, and I want there is only one instance of the service. I have two buttons to switch the language. When i run the app, I use a pipe to translate content and it works, but the switch buttons don't work. I get an error message:
self.parent.context.use is not a function'.
I guess it's all about some misunderstood about some angular concepts so, anyone can help me to implement a global service correctly?
//Translation service
@Injectable()
export class TranslateService {
private _currentLang: string;
constructor(){
this._currentLang = 'es';
}
public get currentLang() {
return this._currentLang;
}
public use(lang: string): void {
// set current language
this._currentLang = lang;
}
private translate(obj : LocalizedData): string {
// private perform translation
return obj[this._currentLang];
}
public instant(obj: LocalizedData ) {
// call translation
return this.translate(obj);
}
}
//Navbar Module
@NgModule({
imports: [ CommonModule, FormsModule],
declarations: [ NavbarMenuComponent, TranslatePipe],
exports: [ NavbarMenuComponent]
})
export class NavbarModule { }
//App component
@Component({
selector: 'app',
template:'<navbar-menu ></navbar-menu>'
})
export class AppComponent implements OnInit{
public translatedText : string;
constructor(){}
ngOnInit(){}
}
//app Module
@NgModule({
imports: [ BrowserModule, FormsModule, NavbarModule],
declarations: [ AppComponent],
bootstrap: [ AppComponent],
providers: [ TranslateService],
})
export class AppModule { }
//Main
const platform = platformBrowserDynamic();
platform.bootstrapModule(AppModule,[ TranslateService]);
Singleton services. Dependencies are singletons within the scope of an injector.Minimal. Providing all your code like above adds too much noise to your question.