将全局服务传递给 child 类 in Angular 2

Pass global service to child classes in Angular 2

我得到了包含 2 个 child 组件和一项服务的主要组件。我做 bootstrap(Main, [MyService]),但是我想从这两个 child 组件中获得功能(调用服务函数的可能性)。我应该如何将此服务的一个实例从 parent 组件传递到我的 child 组件?

不要在组件中指定服务的提供者,只需将其包含在构造函数中即可。

如果您在 bootstrap 中提供服务并希望它是单例,您的组件将如下所示。

@Component({
   template: '<child-component></child-component>',
   directives: [ChildComponent],
   providers: []  // no need to include the specify the service here
 })

export class MyComponent {
  /*even though you're injecting the service here, it will use the same
    instance provided in the bootstrap */

  constructor(private myService: MyService) {
    
  }
}

@Component({
  selector: 'child-component',
  providers: [] // no need to include the specify the service here
})

export class ChildComponent {
  //you can do this as long as you don't specify the service in the providers list
  constructor(private myService: MyService) {
  }
}