我在官方文档和网络上都没有发现 Angular 2 服务是否支持生命周期挂钩的信息。大多数钩子没有意义,但至少ngOnInit()可以非常有用。
实验表明ngOnInit()on an@Injectable()导致服务在引导过程中被实例化,即使它没有用户,但它没有被调用。下面是代码演示:
import { NgModule, Inject, Injectable, OnInit, Component } from '@angular/core'
import { BrowserModule } from '@angular/platform-browser'
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
@Component({
template: 'test',
selector: 'my-component'
})
export class MyComponent {
}
@Injectable()
export class MyService /*implements OnInit*/ {
constructor() {
console.debug('constructing MyService');
}
ngOnInit(): void {
console.debug('MyService.ngOnInit');
}
}
@NgModule({
imports: [ BrowserModule ],
providers: [
MyService
],
declarations: [MyComponent],
bootstrap: [ MyComponent ]
})
class …Run Code Online (Sandbox Code Playgroud)