Dependency injection 角2嵌套注入

Dependency injection 角2嵌套注入,dependency-injection,angular,angular-providers,Dependency Injection,Angular,Angular Providers,我正在与angular2的依赖注入作斗争。在我的示例中,我有两个服务 Service1注入Service2并从中获取数据 组件注入Service1并从Service1获取数据 我必须在我的组件中提供服务2 @Component({ providers: [Service1, Service2] }) 但是为什么呢?我在Service1中注入Service2。为什么我必须在我的组件中提供服务2,而我的组件中没有对服务2的引用? 我知道,我可以在bootsrap函数中提供服务,但我想为我的

我正在与angular2的依赖注入作斗争。在我的示例中,我有两个服务

  • Service1注入Service2并从中获取数据
  • 组件注入Service1并从Service1获取数据
我必须在我的组件中提供服务2

@Component({
  providers: [Service1, Service2]
})
但是为什么呢?我在Service1中注入Service2。为什么我必须在我的组件中提供服务2,而我的组件中没有对服务2的引用?

我知道,我可以在bootsrap函数中提供服务,但我想为我的组件提供服务

bootstrap(AppComponent, [... Service1, Service2])
下面是我的示例代码,由于缺少提供程序,该代码不起作用

组件。ts

import {Service1} from "service1.ts";    

@Component({
  providers: [Service1]
})
export class Component{
  constructor(private s: Service1) {
    //get data from Service1
  }
}
import {Service2} from "service2.ts";

@Injectable()
export class service1{
  constructor(private s2: Service2) {
    //get data from service2
    //edit data
    //return data
  }
}
@Injectable()
export class service2{
  constructor() {
    //return data
  }
}
service1.ts

import {Service1} from "service1.ts";    

@Component({
  providers: [Service1]
})
export class Component{
  constructor(private s: Service1) {
    //get data from Service1
  }
}
import {Service2} from "service2.ts";

@Injectable()
export class service1{
  constructor(private s2: Service2) {
    //get data from service2
    //edit data
    //return data
  }
}
@Injectable()
export class service2{
  constructor() {
    //return data
  }
}
服务2.ts

import {Service1} from "service1.ts";    

@Component({
  providers: [Service1]
})
export class Component{
  constructor(private s: Service1) {
    //get data from Service1
  }
}
import {Service2} from "service2.ts";

@Injectable()
export class service1{
  constructor(private s2: Service2) {
    //get data from service2
    //edit data
    //return data
  }
}
@Injectable()
export class service2{
  constructor() {
    //return data
  }
}

Angular需要知道在哪里可以找到服务。这就是providers数组(在组件或引导调用中)的用途。您可以将其视为分层注册表。如果希望注入服务,则需要将它们提供给注册表

在Angular1中,通过调用
工厂
函数或类似函数在注册表中注册服务。这里的逻辑是不同的


总之,即使组件没有直接绑定到服务,它也必须注册它,以便Angular意识到它的存在。

理论上,您所做的是正确的。您收到了什么错误消息?原始异常:服务2没有提供程序!哦,糟糕,我以为你在引导中提供了这两种服务@smyk的答案是正确的。DI依赖于组件树。感谢您清理它。所以没有办法“隐藏”服务2?这意味着,我必须始终提供并导入我的服务1中使用的所有服务,对吗?对我来说似乎有点不方便…对。您必须明确指定Service2作为应用程序中的某个提供者。