Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ngOnDestroy not fired when service is provided using useFactory

Tags:

angular

HelloComponent gets a SampleService instance, defining a Service Provider. When HelloCompoment is destroyed, I don't understand why SampleService survives.

If HelloComponent got a SampleService instance by type (avoiding ServiceProvider), no problem occurs.


sample-service.ts

@Injectable()
export class SampleService implements OnDestroy{

 constructor(){
   console.log('created new sample service');
 }

 ngOnDestroy(){
  console.log('destroyed sample service');
 }
}

hello-component.ts

import { Component, OnInit, OnDestroy } from '@angular/core'
import { SampleService } from '../service/sample.service'

let ServiceFactory = () => {
  console.log('Providing new SampleService');
  return new SampleService();
};

let ServiceProvider = { 
    provide: SampleService,
    useFactory: ServiceFactory
  };

@Component({
  selector: 'hello',
  templateUrl: './hello.component.html',
  providers: [ServiceProvider]
})
export class HelloComponent implements OnInit, OnDestroy {

constructor(private sampleService: SampleService){}

ngOnInit(){
  console.log("Hello component created!")
}

ngOnDestroy(){
  console.log("Hello component destroyed!")
 }
}

Here stackblitz: https://stackblitz.com/edit/angular-vkhmma (click on toggleHello and see console logs)

How could I force the service destroying when component ends?

like image 574
Fabio Formosa Avatar asked Dec 29 '25 09:12

Fabio Formosa


1 Answers

This is a known issue in Angular, but one that is (unfortunately) by design.

The presence of an OnDestroy callback hook is checked at compile time and since your ServiceProvider is wrapping a Factory which creates a SampleService, the Angular compiler unfortunately has no idea that this hook even exists, so it will never be called.

like image 51
Darren Ruane Avatar answered Dec 30 '25 22:12

Darren Ruane



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!