首页 > 解决方案 > 使用 useFactory 提供服务时未触发 ngOnDestroy

问题描述

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

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


示例服务.ts

@Injectable()
export class SampleService implements OnDestroy{

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

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

你好-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!")
 }
}

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

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

标签: angular

解决方案


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

OnDestroy回调钩子的存在是在编译时检查的,因为你ServiceProvider包装了一个创建 的工厂,SampleService不幸的是,Angular 编译器不知道这个钩子甚至存在,所以它永远不会被调用。


推荐阅读