【问题标题】:Can Injectable Services have a providers list?Injectable Services 可以有提供者列表吗?
【发布时间】:2018-04-17 00:43:09
【问题描述】:

我正在使用组件类和服务类编写一些代码。

@Injectable()
class MyService extends Object {
  ...
}

@Component(
  ...
  providers: const [MyService]
)
class myCompoment implements onInit {
  final MyService _service;
  MyComponent(this._service);
  ...
}

有没有办法说,为我的可注入服务提供一个提供程序,以便它可以使用?在网上看的时候,它显示 Component 来自 Injectable,所以我想从服务中创建一个组件,但这对我来说不太有意义,因为组件也有 UI。

理想情况下,我想做这样的事情:

@Injectable()
class AnotherClass {}

@Injectable(providers: const [AnotherClass])
class MyService extends Object {
  ...
}

@Component(
  ...
  providers: const [MyService]
)
class myCompoment implements onInit {
  final MyService _service;
  MyComponent(this._service);
  ...
}

但 Injectable 似乎不允许提供 providers 属性。

【问题讨论】:

  • 我还不明白你为什么要将提供者添加到@Injectable()

标签: dart angular-dart


【解决方案1】:

您可以将providers: const [MyService, AnotherClass] 添加到组件中,MyService 可以注入 AnotherClass,只需将其列为构造函数参数即可

@Injectable()
class AnotherClass {}

@Injectable()
class MyService extends Object {
  final AnotherClass _anotherClass;

  MyService(this._anotherClass);
}

@Component(
  ...
  providers: const [MyService, AnotherClass]
)
class myCompoment implements onInit {
  final MyService _service;
  MyComponent(this._service);
  ...
}

【讨论】:

  • 这是有道理的,因为 myComponent 有它有一个提供者,它会沿着调用链查找要使用的实例。如果 myComponent 没有它作为提供者,我认为它不会起作用。我想你需要将它添加到 MyService 的某个地方?
  • 服务在提供它们的地方被实例化。他们没有自己的等级制度。它们遵循组件层次结构。因此在服务中添加提供者是没有意义的。
  • 我想你是对的,我试图理解如果我说没有提供它会发生什么。这会导致错误还是会因为不存在而实现自己的实例?我认为它不会,因为您没有告诉它需要它,对吧?
  • 如果 Angular 尝试创建组件或服务的实例,因为无法解析所需的构造函数参数(未找到提供程序),则会引发异常。
  • 有道理。它只是一个运行时异常,因为它不是通过智能感知等来确定的
猜你喜欢
  • 2022-11-14
  • 2020-06-08
  • 2019-01-04
  • 2018-08-30
  • 2019-03-07
  • 2013-02-14
  • 1970-01-01
  • 2010-10-01
  • 2014-04-25
相关资源
最近更新 更多