Life-cycle methods for services in angular2

<>

This question already has an answer here:

Answers


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

When an object of your class is created, 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. The only thing that might happen is that it gets garbage collected once there is no longer a reference to it, which likely happens after the dependency injector is removed itself. But you generally have no control over it, and there is no concept of a deconstructor in JavaScript.

@Injectable()
export class SampleService {
    constructor() {
        console.log('Sample service is created');
    }
}

The ngOn* lifecycle hooks you show are only for components. You could inject another service (call it TrackServiceLifecycles) into SampleService and have SampleService's constructor() call a method on the other service to inform it that it was created. But I can't think of a way to notify the other service when SampleService is destroyed (garbage collected).

See also ECMAScript 6 class destructor


Need Your Help

Eclipse Autocomplete for top level object?

eclipse autocomplete

I have a "Pear" object that inherits from "Fruit"

Sorting Wordpress Custom Meta Box value by date

php wordpress sorting loops meta

I'm working on a custom events post type for a wordpress theme and I'm running into a sorting problem. Everything works as I need until I spit out the values to the template. I need the events to be