I'm feeling a bit lost when it comes to singleton services in Angular 2. I need a translation service that will be accessible throughout the entire application, and I want to ensure that only one instance of the service exists. My issue arises when trying to implement two language switch buttons. While my content translation works fine using a pipe, the switch buttons throw an error message:
'self.parent.context.use is not a function'.
I believe this error stems from a misunderstanding of certain Angular concepts. Can someone provide guidance on how to correctly implement a global service?
//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 {
// perform translation privately
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]);