gpt4 book ai didi

angular - 何时通过依赖注入(inject)创建服务

转载 作者:行者123 更新时间:2023-12-02 18:01:28 25 4
gpt4 key购买 nike

我有一个 Angular 服务,其构造函数中包含一些初始化代码。何时调用此代码,即何时创建服务?

  • 已经在某个模块中提供服务了吗?
  • 或者直到第一个组件注入(inject)它为止?

最佳答案

取自 official docs :

When Angular discovers that a component depends on a service, it first checks if the injector has any existing instances of that service. If a requested service instance doesn't yet exist, the injector makes one using the registered provider, and adds it to the injector before returning the service to Angular.

When all requested services have been resolved and returned, Angularcan call the component's constructor with those services as arguments.

因此,服务似乎仅在第一次需要时才被实例化。

事实上,Angular 甚至可以识别该服务是否永远不会被使用,并在不需要时将其从构建中删除(取自 herehere )。

自己测试一下

验证这一点的一个简单测试是将 console.log 放入组件和它所依赖的服务中,以查看它们的调用顺序。

关于angular - 何时通过依赖注入(inject)创建服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57706800/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com