Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 315
Marcel Šebek Avatar asked Jan 30 '17 18:01

Marcel Šebek


2 Answers

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().

like image 179
Alexander Abakumov Avatar answered Sep 25 '22 21:09

Alexander Abakumov


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.

like image 42
Mezo Istvan Avatar answered Sep 24 '22 21:09

Mezo Istvan