angular2中服务的生命周期方法

Mar*_* C. 33 dependency-injection angular

是否可以为带有注释的服务提供生命周期挂钩@Injectable()

我曾经期望在这样的服务上调用生命周期钩子,但我被证明是错误的,它似乎@Component只是在工作.当依赖注入创建/销毁服务时,有没有办法在服务中获得信息?

import {Component, Injectable, OnInit, OnDestroy} from 'angular2/core';

@Injectable()
export class SampleService implements OnInit, OnDestroy {
    ngOnInit() {
        console.log("OnInit")
    }
    ngOnDestroy() {
        console.log("OnDestroy")
    }
}

@Component({
  selector: "sample",
  template: "<div>Sample Component</div>",
  providers: [ SampleService ]
})
export class SampleComponent {
  constructor() { private _sampleService: SampleService }
}
Run Code Online (Sandbox Code Playgroud)

pok*_*oke 33

注入只是普通类(普通对象),因此它们没有特殊的生命周期.

当创建类的对象时,将调用类的构造函数,这就是"OnInit"的含义.至于破坏,服务并没有真正被破坏.唯一可能发生的事情是,一旦不再引用它就会收集垃圾,这可能发生在依赖注入器自身被删除之后.但是你通常无法控制它,并且JavaScript中没有解构函数的概念.

@Injectable()
export class SampleService {
    constructor() {
        console.log('Sample service is created');
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 销毁服务时会调用[ngOnDestroy](https://angular.io/api/core/OnDestroy). (7认同)
  • @AlexVauch这将告诉你*什么时候*服务被销毁,但它不能让你控制实际销毁服务. (3认同)

Mar*_*cok 10

您显示的ngOn*生命周期挂钩仅适用于组件.您可以将另一个服务(称为TrackServiceLifecycles)注入SampleService,并让SampleService的构造函数()调用另一个服务上的方法,以通知它已创建.但是,当SampleService被销毁(垃圾收集)时,我想不出一种通知其他服务的方法.

另请参见ECMAScript 6类析构函数