【问题标题】:DI, constructor, and field initialization execution orderDI、构造函数、字段初始化执行顺序
【发布时间】:2022-06-10 18:07:25
【问题描述】:

我在 Angular 中有以下示例代码:

@Injectable({
    providedIn: 'root',
})
export class MyService {

    constructor(private dependentService: DependentService) {} // this is called second
    public myField$ = this.init() // this is called first

    init(){
        return this.dependentService.getAnObservable()
    }
}

MyService 被实例化时:

  • myField$ 在调用 constructor 之前首先被初始化。我可以通过使用例如 console.log

    来验证这一点
  • 但是,myField$ 初始化依赖于 dependentService,它再次通过 构造函数

    注入

那怎么可能没有任何错误呢?

【问题讨论】:

  • 只需在ctor(?)中分配myField$

标签: angular ecmascript-6 dependency-injection es6-class


【解决方案1】:

您应该看看您的示例如何编译为 javascript - 我已经为您将它导入到 Playground here

如您所见,首先将构造函数参数中的字段赋值,然后初始化构造函数外部的字段,然后才执行构造函数体。

【讨论】:

    猜你喜欢
    • 2017-06-20
    • 2011-05-01
    • 2013-01-29
    • 2012-03-19
    • 1970-01-01
    • 2021-06-12
    • 2010-11-17
    相关资源
    最近更新 更多