【发布时间】:2017-01-30 18:20:00
【问题描述】:
我在官方文档和网络上都没有发现 Angular 2 服务是否支持生命周期挂钩的信息。大多数钩子没有意义,但至少ngOnInit() 可能非常有用。
实验表明,@Injectable() 上的 ngOnInit() 导致服务在引导期间被实例化,即使它没有用户,但它没有被调用。下面是代码演示:
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 AppModule {
}
console.debug('bootstrapping');
platformBrowserDynamic().bootstrapModule(AppModule);
https://plnkr.co/edit/98Q9QqEexYoMRxP3r1Hw?p=info
这是设计使然吗?如果是这样,它可能应该被记录在案。如果不是,则应更改。
此问题源于此(大部分已修复)问题:
https://github.com/angular/angular/issues/13811
我不清楚场景 1(问题的非固定部分)是否是有效代码。
【问题讨论】:
-
Marcel,你能接受我的回答吗?或者让我知道我该如何修改它?
标签: angular typescript angular2-services