What is the lifecycle of a service in Angular 5

Services can have 2 scopes.

If a service is declared in your module, you have the same instance shared for all, this means the service will be constructed when the first component/directive/service/Pipe who needs it will be created. Then it will be destroyed when the Module itself will be destroyed (most of the time when the page is unloaded)

if the service is declared on Component/Directive/Pipe, then a separate instance will be created each time a Component/Directive/Pipe will be created and destroyed when related Component/Directive/Pipe will be destroyed.

You can see it in action

Code testing : 2 services are made for showing when they are created/destroyed.

@NgModule({
  providers: [GlobalService] // This means lifeCycle is related to the Module, and only one instance is created for the whole module. It will be created only when the first element who needs it will be created.
})
export class AppModule { }

The second service is a local component service and will be created for each hello-component instance created, and destroyed just before hello-component will be destroyed.

@Injectable()
export class LocalService implements OnDestroy{
  constructor() {
    console.log('localService is constructed');
  }

  ngOnDestroy() {
    console.log('localService is destroyed');
  }
}

@Component({
  selector: 'hello',
  template: `<h1>Hello {{name}}!</h1>`,
  styles: [`h1 { font-family: Lato; }`],
  providers: [LocalService]
})
export class HelloComponent implements OnInit, OnDestroy {
  @Input() name: string;

  constructor(private localService: LocalService, private globalService: GlobalService) {}

  ngOnInit(){
    console.log('hello component initialized');
  }

  ngOnDestroy() {
    console.log('hello component destroyed');
  }
}

As you can see, a Service in angular can have an OnDestroy life cycle hook.

Leave a Comment