Service lifecycle methods in angular2

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

I would expect lifecycle hooks to be called for such a service, but I turned out to be wrong, it seems to work only on @Component . Is there a way to get information 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 } } 
+22
dependency-injection angular
Mar 23 '16 at 21:24
source share
2 answers

Injections are just normal classes (ordinary objects), and therefore they do not have a special life cycle.

When an object of your class is created, the class constructor is called, so it will be your "OnInit". With regard to destruction, the service is really not destroyed. The only thing that can happen is that it receives garbage collection when there is no longer a reference to it, which is likely to happen after the dependency injectors are removed themselves. But you do not control it at all, and in JavaScript there is no concept of a deconstructor.

 @Injectable() export class SampleService { constructor() { console.log('Sample service is created'); } } 
+23
Mar 23 '16 at 21:40
source share

The ngOn * lifecycle hooks you show are for components only. You can enter another service (name it TrackServiceLifecycles) in SampleService and create the SampleService () constructor on another service to tell it that it was created. But I cannot think of a way to notify another service when the SampleService is destroyed (garbage collection).

See also ECMAScript 6 class destructor

+6
Mar 23 '16 at 21:40
source share



All Articles