Angular 2 分层依赖注入 - 在根之外声明根提供者的依赖?

Angular 2 Hierarchical Dependency Injection - Declaring root provider's dependencies outside of root?

(注意我使用的是 Angular 2 RC5)

为简单起见,我有一个这样的应用程序:

app.module.ts

@NgModule({
    providers: [
        RootService
    ],
    entryComponents: [AppComponent],
    bootstrap: [AppComponent]
})

export class AppModule {}

root.service.ts

import Dependency1 from './somewhere'
import Dependency2 from './somewhere-else'

@Component({
    providers: [Dependency1, Dependency2]
})

@Injectable()
export class RootService {
    constructor(
        private dep1: Dependency1, 
        private dep2: Dependency2
    ) {...}
}

依赖的一个例子是:

dependency1.ts

@Injectable()
    export class Dependency1{
    public doGroundbreakingSciencyStuff() {...}
}

我的问题是:为什么在上述情况下,我会收到一条错误消息: No provider for PouchSync!.

我可以通过将 Dependency1 和 Dependency2 添加到 app.module.ts 中的 providers 数组来解决问题,如下所示:

app.module.ts(固定)

@NgModule({
    providers: [
        RootService,
        Dependency1,
        Dependency2
    ],
    entryComponents: [AppComponent],
    bootstrap: [AppComponent]
})

export class AppModule {}

这看起来很丑陋。只有 RootService 需要了解这些依赖项。我在这里做错了什么吗?或者有人可以解释为什么必须这样吗?当然,当注入 RootService 时,注入器可以看到它依赖于 Dependency1Dependency2,因此也必须注入它们,因此它们也将是应用程序范围的单例。

服务不是组件,所以它们不能有@Component装饰器(这意味着 - 不可能添加供应商数组用于服务 class)。结论?此代码错误:

@Component({
    providers: [PouchSync, PouchArraySync]
})

@Injectable()
export class RootService {
    constructor(
        private dep1: Dependency1, 
        private dep2: Dependency2
    ) {...}
}

但是你的 second 例子是用 angular 2 种方式制作的。

您写道,只有 RootService 需要了解相关性。因此,如果这些依赖项不是 可重用对象 ,它们应该被注入到你的应用程序的几个部分中,但只在这个 class(!) 中可用 - 你应该只创建实例他们在你的服务中。

您要在应用程序中使用的任何服务都必须添加到提供程序数组中。向根 ngModule 添加服务实际上使它们在整个应用程序中可用。

当你这么说的时候 "Surely, when injecting RootService, the injector can see that it's dependent on Dependency1 and Dependency2 and hence must inject those too, and hence they'll also be application wide singletons".

没有注入器不会通过只添加RootService自动添加Dependency1和Dependency2。它们必须专门添加到提供程序数组