小编Mar*_*bek的帖子

服务的生命周期钩子

我在官方文档和网络上都没有发现 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)

typescript angular2-services angular

8
推荐指数
2
解决办法
7306
查看次数

标签 统计

angular ×1

angular2-services ×1

typescript ×1