Marcel Šebek
Marcel Šebek

Reputation: 311

Lifecycle hooks for services

I've found no information whether lifecycle hooks are supported on Angular 2 services, neither in the official documentation, nor on the web. Most hooks do not make sense, but at least ngOnInit() can be very useful.

Experiment shows that ngOnInit() on an @Injectable() causes the service to be instantiated during bootstrap even though it has no users, but it is not called. Here is a code demonstration:

import { NgModule, Inject, Injectable, OnInit, Component } from '@angular/core'
import { BrowserModule } from '@angular/platform-browser'
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

@Component({
  template: 'test',
  selector: 'my-component'
})
export class MyComponent {
}

@Injectable()
export class MyService /*implements OnInit*/ {
  constructor() {
    console.debug('constructing MyService');
  }

  ngOnInit(): void {
    console.debug('MyService.ngOnInit');
  }
}

@NgModule({
  imports: [ BrowserModule ],
  providers: [
    MyService
  ],
  declarations: [MyComponent],
  bootstrap: [ MyComponent ]
})
class AppModule {
}

console.debug('bootstrapping');
platformBrowserDynamic().bootstrapModule(AppModule);

https://plnkr.co/edit/98Q9QqEexYoMRxP3r1Hw?p=info

Is this by design? If so, it should probably get documented. If not, it should be changed.

This problem originates from this (mostly fixed) issue:

https://github.com/angular/angular/issues/13811

It is not clear to me whether the scenario 1 (non-fixed part of the issue) is a valid code or not.

Upvotes: 11

Views: 12715

Answers (3)

Alexander Abakumov
Alexander Abakumov

Reputation: 14539

The only lifecycle hook which is called for Angular 2 services is ngOnDestroy():

A lifecycle hook that is called when a directive, pipe, or service is destroyed. Use for any custom cleanup that needs to occur when the instance is destroyed.

As for the ngOnInit(), it's not called because it doesn't make sense :) You should put a service initialization logic into its constructor().

Upvotes: 13

sparebytes
sparebytes

Reputation: 13096

In my testing ngOnDestroy is called but ngOnInit is not called on services.

This is with [email protected]. Unfortunately I can't find any documentation on it.

Upvotes: 2

Mezo Istvan
Mezo Istvan

Reputation: 2772

In this guide: https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html it is stated that lifecycle hooks are only called on directives and components. So unfortunately, they shouldn't be used on services.

Upvotes: 3

Related Questions