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; 
1
  • place it inside constructor of productService Commented Jan 3, 2018 at 9:16

2 Answers 2

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; } 
Sign up to request clarification or add additional context in comments.

1 Comment

You can press in tick mark. Showing next to the answer. stackoverflow.com/help/someone-answers
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.

2 Comments

The answer surely helps. Just update the lifecycle hooks URL. It is currently redirecting to an error page because of invalid URL. Cheers!
The life cycle hooks are only applicable for components and directive. I think here OP refers to a service. stackoverflow.com/questions/36188966/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.