1

Is it possible to execute some code when a service is initialized. For example when the service product Service is initialized I would want to execute this code:

this.var = this.sharedService.aVar;
Cœur
  • 37,241
  • 25
  • 195
  • 267
Nicolas Alain
  • 105
  • 11

2 Answers2

3

Other than constructor there is NO lifecycle hooks for Service..

Lifecycle hooks are supported by component/directive

Injectables are normal classes (normal objects) and as such, they have no special lifecycle.

@Injectable()
   export class SampleService {
    constructor() {
        console.log('Sample service is created');
        //Do whatever you need when initialized.
    }
}

the class’s constructor is called, so that’s what your “OnInit” would be. As for the destruction, a service does not really get destroyed.

where a service needs another service use dependency injection

@Injectable()
export class HeroService { 


private yourVariable: any;
constructor(private sharedService: sharedService) {
  this.yourVariable = this.sharedService.aVar;
}
Eldho
  • 7,795
  • 5
  • 40
  • 77
  • You can press in tick mark. Showing next to the answer. https://stackoverflow.com/help/someone-answers – Eldho Jan 06 '18 at 16:19
0

I suggest you read up a little on lifecycle hooks in Angular. While in the constructor is an option it is a good idea to keep the code in that limited to variable initialization and use the ngOnInit lifecycle hook to do class initialization work. Both are an option but understanding the lifecycle hooks is a good starting point in addressing your question and thinking through where you want to do this.

Eldho
  • 7,795
  • 5
  • 40
  • 77
ToddB
  • 1,464
  • 1
  • 12
  • 27
  • The answer surely helps. Just update the lifecycle hooks URL. It is currently redirecting to an error page because of invalid URL. Cheers! – planet_hunter Jan 03 '18 at 10:14
  • 1
    The life cycle hooks are only applicable for components and directive. I think here OP refers to a service. https://stackoverflow.com/questions/36188966/life-cycle-methods-for-services-in-angular2# – Eldho Jan 03 '18 at 10:46