Amit
Amit

Reputation: 6294

AngularJS 2 localization service best practice

I have a service, in which I can call:

localization('navbar.home')

And it returns 'Home'.

A few questions:

  1. At the moment, I have to inject this service to every component I work with, and then I write let lang = localization;, Is there a way to bind it into something like NG1 $rootScope, so I'll have to load it once?
  2. Is there a way to one time bind the function? NG1 gave me the option to write: {{::lang('navbar.home')}}, so it was only called once.

My attitude for localization may be totally outdated, or wrong, because I am migrating from NG1.

What is the best practice here? Keep it as a service? Not bind it once?

Upvotes: 1

Views: 455

Answers (1)

Sasxa
Sasxa

Reputation: 41264

Injected services are inherited, you can inject them just once at root level (bootstrap) if you wish to use them in all components:

bootstrap(AppComponent, [
/* everything you put here is available  in all components */ 
  ServiceOne,
  ServiceTwo
])

You'll still need to declare them in your components' constructor:

constructor(private so: ServiceOne) {}

but you don't include them in providers[] metadata of the component.

Can't help with other stuff (;

Upvotes: 1

Related Questions