Life-cycle methods for services in angular2

Viewed 27040

Is it possible to have life-cycle hooks for a service that is annotated with @Injectable()?

I'd have expected the life-cycle hooks to be called on a service like this, but I was proven wrong, it seems to be working on @Component only. Is there a way to get informed in a service when dependency injection creates / destroys a service?

import {Component, Injectable, OnInit, OnDestroy} from 'angular2/core';

@Injectable()
export class SampleService implements OnInit, OnDestroy {
    ngOnInit() {
        console.log("OnInit")
    }
    ngOnDestroy() {
        console.log("OnDestroy")
    }
}

@Component({
  selector: "sample",
  template: "<div>Sample Component</div>",
  providers: [ SampleService ]
})
export class SampleComponent {
  constructor() { private _sampleService: SampleService }
}
2 Answers
Related