【问题标题】:Lifecycle hooks for services服务的生命周期钩子
【发布时间】: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


【解决方案1】:

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

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

至于ngOnInit(),它没有被调用,因为它没有意义:) 你应该将服务初始化逻辑放入它的constructor()

【讨论】:

  • 我想在初始化过程中添加一个异步操作,但是在构造函数内部你不能有异步。在这种情况下,在 ngOnInit() 内部实现是有意义的。
  • @NesredinMahmud,您实际上可以从构造函数中调用async 方法,只是不能await 它。这与从 ngOnInit 调用甚至等待它没有什么不同,因为 Angular 从来没有 awaits 生命周期钩子方法。因此,在服务中使用ngOnInit 仍然没有意义。
【解决方案2】:

在本指南中:https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html 指出,生命周期挂钩仅在指令和组件上调用。所以很遗憾,它们不应该用在服务上。

【讨论】:

    【解决方案3】:

    在我的测试中,ngOnDestroy 被调用,但 ngOnInit 未被服务调用。

    这是 Angular@6.1.4。不幸的是,我找不到任何关于它的文档。

    【讨论】:

      猜你喜欢
      • 2020-01-15
      • 2017-11-22
      • 1970-01-01
      • 1970-01-01
      • 2018-03-13
      • 2018-08-30
      • 2016-08-26
      • 1970-01-01
      相关资源
      最近更新 更多