服务的生命周期钩子函数

10

我没有找到任何信息表明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,你能接受我的答案或者让我知道如何修改它吗? - Alexander Abakumov
3个回答

13
Angular 2服务中唯一被调用的生命周期钩子是ngOnDestroy()

当指令、管道或服务被销毁时调用的生命周期钩子。用于任何需要在实例被销毁时进行清理的自定义逻辑。

至于ngOnInit(),它不会被调用,因为这没有意义 :) 您应该将服务初始化逻辑放入其constructor()中。

1
我想在初始化期间添加一个异步操作,但是在构造函数内部不允许使用async。在这种情况下,实现ngOnInit()内部是有意义的。 - Nesredin Mahmud
@NesredinMahmud,你实际上是允许从构造函数调用async方法的,只是不能使用await。这与从ngOnInit调用或甚至等待它没有任何区别,因为Angular从不等待生命周期钩子方法。因此,在服务中仍然使用ngOnInit是没有意义的。 - Alexander Abakumov

3

2
在我的测试中,ngOnDestroy被调用了,但是服务中的ngOnInit没有被调用。这是使用Angular@6.1.4版本时发生的。不幸的是,我找不到任何相关文档。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接