Miguel
Miguel

Reputation: 787

Singleton service in Angular 2

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]);
 

Upvotes: 2

Views: 1058

Answers (1)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657318

In Angular2 services are singletons per provider. If you provide a service multiple times, you'll get multiple instances.

If you provide it in

@NgModule({ 
  providers: [SomeService]
  ...
})

then it will be provided at the root scope and you'll get a single instance for your whole application. Even when more than one @NgModule() contains a service in providers, you'll get only one instance because they are hoisted in the application root scope.

Lazy loaded modules have their own root scope.

If you provide a service in @Component() every such component instance and it's children will get a different service instance.

Upvotes: 3

Related Questions