将服务注入另一个服务 [英] Inject a service into another service

查看:108
本文介绍了将服务注入另一个服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将一个服务注入另一个服务,但是由于某种原因, @ Inject装饰器将被忽略。例如,以下服务依赖于另一个服务:

I would like to inject a service into another service but, for some reason, the "@Inject" decorator is being ignored. For example, the following service depends on another service:

@Injectable()
class MyService {
    final AnotherService _service;
    MyService(@Inject(AnotherService) this._service);
// ... more methods
}

Angular2抛出以下错误:

Angular2 throws the following error:


原始例外:没有其他服务提供者!

ORIGINAL EXCEPTION: No provider for AnotherService!

我是否以一种不好的方式使用了 @Inject装饰器?

Am I using the "@Inject" decorator in a bad way?

推荐答案

缺少某些信息无法完全解决这是一个例外,但说明喷射器没有足够的信息来解析 AnotherService

Some information is missing to fully solve this but exception says that the injector doesn't have enough information to resolve AnotherService

角度的DI是基于层次结构构建的,从

The DI in angular is build upon hierarchies, starting from the root injector which is created upon an angular application bootstrap.

每个层次结构都是一个新的注入器实例,从下到上解决依赖关系,即:如果注入器可以无法解决它将要求其父母解决。这将一直持续到到达没有父级的注入器(根注入器)为止。

Each hierarchy is a new injector instance, resolving a dependency is done from bottom to top, i.e: if an injector can't resolve it will ask its parent to resolve. This will go on until it reach an injector without a parent (root injector).

在声明MyService的提供者之前,请确保已声明AnotherService的提供者。

Make sure you declare a provider for AnotherService before you declare a provider for MyService.

只需在提供的引导程序提供程序数组中将提供程序添加到AnotherService。

Just add a provider to AnotherService in the providers array you supply to bootstrap.

这篇关于将服务注入另一个服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆