I built a service that called lang.service.ts
. What it does is simply a key: value
mechanism. Whenever I need it to my component, I import it and declare it in the constructor
and then I use it as {{lang('key').text}}
. so far, so good.
The thing is that I've noticed that I'm gonna load it for each component, like for view-header.component.ts
, view-footer.components.ts
and a lot of other components. I never used Angular 1, but IIRC, I could do there something like rootScope.lang(..)
and it could've accomplish what I was looking for. Is there a way to do something like that in Angular 2?
If you register your service at your root componet, all child components will have access to the service.
On your root component...
import { Component } from '@angular/core';
import { YourService } from './my-servive.service.ts';
import { ChildComponent } from './child-component.component.ts';
@Component({
selector: 'root-component',
providers: [YourService],
directives: [ChildComponent],
template: `<child-component></child-component>`
})
export class RootComponent {}
On your child component...
import { Component } from '@angular/core';
import { YourService } from './my-servive.service.ts';
@Component({
selector: 'child-component'
})
export class ChildComponent {
contructor(private myService: YourService) {}
}
Hope this help you.