Nicolas Alain
Nicolas Alain

Reputation: 105

Executing some code when a service is initialized

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;

Upvotes: 1

Views: 56

Answers (2)

Eldho
Eldho

Reputation: 8263

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;
}

Upvotes: 3

ToddB
ToddB

Reputation: 1474

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.

Upvotes: 0

Related Questions