使用 useFactory 提供服务时不会触发 ngOnDestroy

Fab*_*osa 3 angular

HelloComponent获取一个SampleService实例,定义一个服务提供者。当HelloCompoment被摧毁时,我不明白为什么SampleService还能幸存。

如果按类型HelloComponent获取SampleService实例(避免ServiceProvider),则不会出现问题。


样本服务.ts

@Injectable()
export class SampleService implements OnDestroy{

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

 ngOnDestroy(){
  console.log('destroyed sample service');
 }
}
Run Code Online (Sandbox Code Playgroud)

你好组件.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!")
 }
}
Run Code Online (Sandbox Code Playgroud)

这里 stackblitz:https://stackblitz.com/edit/angular-vkhmma (单击toggleHello 并查看控制台日志)

当组件结束时,如何强制销毁服务?

Dar*_*ane 5

这是 Angular 中的一个已知 问题,但(不幸的是)这是设计使然的问题。

回调钩子的存在会在编译时OnDestroy被检查,并且由于您正在包装一个创建 的工厂,不幸的是,Angular 编译器不知道这个钩子存在,所以它永远不会被调用。ServiceProviderSampleService